how to check if listview item is checked
Solution 1
Which event are you capturing? Remember if it's the ItemCheck
, that you cannot use the listView1.Item[0].Checked
if that item was what was checked/unchecked. You need to take the ItemCheckEventArgs
parameter, and using the e.Index
, exclude that element when checking the entire listview elements. Use e.NewValue
to separately evaluate the item that raised the ItemCheck
event.
Solution 2
Not sure exactly what you're looking for but there are a number ways to determine which items in a ListView are checked:
// This loops through only the checked items in the ListView.
foreach (ListViewItem checkedItem in listView1.CheckedItems) {
// All these ListViewItems are checked, do something...
}
// This loops through all the items in the ListView and tests if each is checked.
foreach (ListViewItem item in listView1.Items) {
if (item.Checked) {
// This ListViewItem is Checked, do something...
}
}
You can use the ListViewItem Class to examine the details of each selected item.
luc
Updated on June 04, 2022Comments
-
luc almost 2 years
User chose a folder containing files. I'm making a listview displaying the files in the chosen folder. I want to display what each file contains, but i want to display it when the user checks a file from listviewitem. I'm using the following code:
if (listView1.Items[0].Checked == true) { //.... }
Why doesn't it work? What should i want to use data from for example:
button1.Click(...)
tobutton2.Click(...)
?-
John Saunders over 13 yearsWhich "ListView"? Web Forms? Windows Forms? WPF? SilverLight?
-
p.campbell over 13 yearsalso consider
if (listView1.Items[0].Checked)
-
NotMe over 13 yearsluc, when posting a question it helps to include things like error messages or at least more detail as to exactly what "doesn't work"
-
luc over 13 yearsthere's no errors or exceptions
-
-
Dan J over 13 yearsThat's not a bad WPF design, but it doesn't answer the OP's question, which was how you determine if an item in a .NET Framework ListView is checked...