10

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;
}
4
  • do you use winforms or wpf? Commented Feb 5, 2013 at 13:06
  • 1
    Define "not working". Do you get a compile-time error, a run-time error, or does the actual behaviour not meet your expected behaviour. Commented Feb 5, 2013 at 13:06
  • Have you done any cut and paste with yourListView in the designer? If so, the event handler is not mapped any more to the SelectedIndexChanged event, unless you reassign it. Commented Feb 5, 2013 at 13:19
  • just small proposal. you can set property FullRowSelect=true for your ListView :) Commented Feb 5, 2013 at 13:27

2 Answers 2

19

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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
}

2 Comments

Can you provide an explanation of the changes you made?
you should always try and use 'var' keyword, since you are working with objects

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.