after selecting a value out of my listview and clicking my button i wanted to get my value into the Code but my code is throwing this exception:
Count = 'this.listView1.SelectedItems.Count' threw an exception of type 'System.InvalidOperationException'
private void OK_button_Click(object sender, EventArgs e)
{
try
{
// OK -> Daten übernehmen
ListView.SelectedListViewItemCollection data = this.listView1.SelectedItems;
int iCount = data.Count;
if (iCount != 1)
{
MessageBox.Show("Value is empty");
return;
}
DialogResult = DialogResult.OK;
Close();
}
catch (Exception ex)
{
//WriteProtokoll(ex.ToString(), 0);
Close();
}
}
}
private void listView1_SearchForVirtualItem(object sender, SearchForVirtualItemEventArgs e)
{
e.Index = Array.FindIndex(myData, s => s == textBox1.Text.ToString());
}
private void listView1_RetrieveVirtualItem(object sender, RetrieveVirtualItemEventArgs e)
{
e.Item = new ListViewItem(myData[e.ItemIndex]);
}
myData = new string[dataListSize];
for (int i = 0; i < dataListSize; i )
{
myData[i] = String.Format("{0}", i);
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
String MyString = textBox1.Text.ToString();
ListViewItem lvi = listView1.FindItemWithText(MyString.TrimEnd());
//Select the item found and scroll it into view.
if (lvi != null)
{
listView1.SelectedIndices.Clear();
listView1.SelectedIndices.Add(lvi.Index);
listView1.EnsureVisible(lvi.Index);
}
}
CodePudding user response:
This is by design when you use VirutalMode
. The documentation states:
In virtual mode, the Items collection is disabled. Attempting to access it results in an InvalidOperationException. The same is true of the CheckedItems collection and the SelectedItems collection.
We can confirm this in the source code.
It goes on to provide the following advice:
If you want to retrieve the selected or checked items, use the SelectedIndices and CheckedIndices collections instead.
You should therefore use this.listView1.SelectedIndices.Count
instead.
Looking at the source code again, we can see that this won't throw an exception.