user2002495 user2002495 - 3 months ago 37
C# Question

How to grab value of selected objects in ObjectListView

I have an objectlistview which displays filename and its path in a column. I would like to run a function on selected items. Is there any way I can grab the value of the filename and loop through every file that is selected on the objectlistview? The column aspect name is Filename.

My function is as follows: sampleFunction(string inputFile, string outputFile);

so far I've tried this, but couldn't work, I know I'm missing reference to the column itself but I don;t know how to add it:

for(var i=0; i<=objectListView1.SelectedObjects.Count; i++)
{
encClass.sampleFunction(objectListView1.SelectedObjects[i], "output here");
}


edit:

I also tried append
ToString()
method to
objectListView1.SelectedObjects[i].ToString()
. It shows no error but the function couldn't run perfectly because I have 3 columns and I only wanted to use the first column's value in the function as the inputFile value.

Answer

I seems that you do not understand the concept of the OLV correctly. I suggest you read the tutorial (again).
The OLV allows you to work with the underlying model objects directly, so just cast the selected object(s) to the original type and access its properties. You can even use a TypedObjectListView<>, which simplifies access to the models.

Judging from you post, what you want to do is probably something like this:

foreach (var selectedObject in objectListView1.SelectedObjects) {
    encClass.sampleFunction(((MyType)selectedObject).Filename, "output here");
}

Obviously, replace "MyType" with your model object type.