Jonhston Hirsh
Jonhston Hirsh

Reputation:

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

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

Upvotes: 11

Views: 22905

Answers (6)

TaTa
TaTa

Reputation: 19

int taskId = Convert.ToInt32(itemRow.SubItems[0].Text);

string taskDate = itemRow.SubItems1.ToString();

string taskDescription = itemRow.SubItems[2].ToString();enter image description here

Upvotes: 0

hetuka kodekar
hetuka kodekar

Reputation: 111

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 

}

Upvotes: -1

Zo.
Zo.

Reputation: 400

//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;
    }
}

Upvotes: -1

Louie Bacaj
Louie Bacaj

Reputation: 1417

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;

Upvotes: 0

Winston Smith
Winston Smith

Reputation: 21922

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

Upvotes: 0

JaredPar
JaredPar

Reputation: 755387

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
}

Upvotes: 21

Related Questions