Tutorial :C#: How do you make sure that a row or item is selected in ListView before performing an action?



Question:

What is the best way to check if there is atleast a selected item in a listview or not in an if statement?


Solution:1

I'm not entirely sure what you are asking. Do you want to make sure at least 1 item is selected before running an action? If so the following should work

if ( listView.SelectedItems.Count > 0 ) {     // Do something  }  

Or are you curious if a particular item is selected? If so try the following

if ( listView.SelectedItems.Contains(someItem)) {     // Do something  }  


Solution:2

if( listView.SelectedItems.Count > 0 ){   // do stuff here  }  


Solution:3

You can also check the value of a selected item or perhaps bind it to a string if needed:

        //Below is with string          String member = (String)ListView1.SelectedValue;            //Below is with any class          AnyClass member = (AnyClass)ListView1.SelectedValue;          String StaffID = member.StaffID;  


Solution:4

//Here a simple loop that go through all the items in the list      for (int i = 0; i < listView1.Items.Count; i++)  {      //checks if the item in the list has the value true to the properties checked         if (listView1.Items[x].Checked == true)      {//your  code          //e.g.           listView1.Items[x].Checked = false;      }  }  


Solution:5

You can also check count of the selected item list by using getCheckedItemCount() method of the listview. for example,

if( listview.getCheckedItemCount() > 0 ) {

 // do stuff here   

}


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »