Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting value from listview control

Tags:

c#

Need help selecting the value from custID column in the ListView so that I can retrieve the value from the database and display it in the TextBoxes.The SelectedIndex not working in c#

Thanks

http://img713.imageshack.us/img713/133/listview.jpg

My Code

private void yourListView_SelectedIndexChanged(object sender, EventArgs e)
{
    if (yourListView.SelectedIndex == -1)
        return;
    //get selected row
    ListViewItem item = yourListView.Items[yourListView.SelectedIndex];
    //fill the text boxes
    textBoxID.Text = item.Text;
    textBoxName.Text = item.SubItems[0].Text;
    textBoxPhone.Text = item.SubItems[1].Text;
    textBoxLevel.Text = item.SubItems[2].Text;
}
like image 714
user2006506 Avatar asked Feb 05 '13 13:02

user2006506


2 Answers

ListView doesn't have property SelectedIndex. You should use SelectedItems or SelectedIndices.

So you can use this:

private void yourListView_SelectedIndexChanged(object sender, EventArgs e)
{
    if (yourListView.SelectedItems.Count == 0)
        return;    

    ListViewItem item = yourListView.SelectedItems[0];
    //fill the text boxes
    textBoxID.Text = item.Text;
    textBoxName.Text = item.SubItems[0].Text;
    textBoxPhone.Text = item.SubItems[1].Text;
    textBoxLevel.Text = item.SubItems[2].Text;
}

I suggested here that property MultiSelect is set to false.

like image 115
algreat Avatar answered Oct 05 '22 09:10

algreat


C# and WPF use this:

private void lv_yourListView_SelectedIndexChanged(object sender, EventArgs 
e)
{
    if (yourListView.SelectedItems.Count == 0)
        return;    

     var item = lvb_listInvoices.SelectedItems[0];
     var myColumnData = item.someField; //use whatever you want
}
like image 30
Eran Peled Avatar answered Oct 05 '22 08:10

Eran Peled