Get Item[i] from listview
I am trying to get an item[i] to a string from a ListView. I just don't seem to understand what I am supposed to do, when the ListView is on another thread.
public delegate void getCurrentItemCallBack (int location);
...
private void runAsThread()
{
While (..>i)
{
//I tried the following //Doesn't work.
//string item_path = listView.Item[i].toString();
//attempting thread safe. How do I get it to return a string?
string item_path = GetCurrentItem(i);
}
}
private void GetCurrentIte开发者_Go百科m(int location)
{
if (this.listViewModels.InvokeRequired)
{
getCurrentItemCallback d = new getCurrentItemCallback(GetCurrentItem);
this.Invoke(d, new object[] { location });
}
else
{
this.listViewModels.Items[location].ToString();
}
}
What am I missing?
You need to have a delegate type that returns a string, not a void, to begin with.
Then, you need the matching method to return a string as well.
public delegate string getCurrentItemCallBack (int location);
...
private string GetCurrentItem(int location)
{
if (this.listViewModels.InvokeRequired)
{
getCurrentItemCallback d = new getCurrentItemCallback(GetCurrentItem);
return this.Invoke(d, new object[] { location });
}
else
{
return this.listViewModels.Items[location].ToString();
}
}
Much easier and readable IMO to use a lambda action, no messing around with callbacks or delegates
private void GetCurrentItem(int location)
{
if (this.listViewModels.InvokeRequired)
{
Invoke( new Action ()=>{
//do what ever you want to do here
// this.listViewModels.Items[location].Text;
}));
}
else
{
this.listViewModels.Items[location].Text;
}
}
精彩评论