Ramesh Sivaraman
Ramesh Sivaraman

Reputation: 1305

selecting item from listview in C#

I am trying to select an item from a list view and it should display each in a text box as I select it. I am able to select and get first item but when I select the second item I am getting an error,

"Argument out of range exception was unhandled, InvalidArgument=Value of '0' is not valid for 'index'."

I have my below code, please help me..

public partial class Form2 : Form
{
  List<Person> people = new List<Person>();
}

class Person
{
  public string Name{ get; set; }

  private void button2_Click(Object sender, EventArgs e)
  {
    Person p = new Person();
    p.Name = textBox1.Text;
    people.Add(p);
    listBox1.Items.Add(p.Name);
  }

  private void listView1_SelectedIndexChanged(object sender, EventArgs e)
  {
    textBox1.Text = people[listView1.SelectedItems[0].Index].Name;
  }
}

Upvotes: 0

Views: 14526

Answers (4)

Epsil0neR
Epsil0neR

Reputation: 1704

if you want to have list your persons and remove List people, you need to do next:

-Add to Person function ToString() which will return Person.Name, ListBox can keep any objects, but showed text is object.ToString()

public override string ToString() 
{
  return Name;
}

-On button click you must add person to listView1, not name of person:

private void button2_Click(object sender, EventArgs e)
{
    Person p = new Person();
    p.Name = textBox1.Text;

    people.Add(p);
    listBox1.Items.Add(p);
}

-Now you can get your person, because listView keep now Person, not String:

private void listView1_SelectedIndexChanged(object sender, EventArgs e)
{
  textBox1.Text = ((Person)listView1.SelectedItems[0]).Name;
}

Upvotes: 0

Akshay J
Akshay J

Reputation: 5458

 private void listView1_SelectedIndexChanged(object sender, EventArgs e)
 {
   if(listView1.SelectedItems.Count > 0)
     textBox1.Text = people[listView1.SelectedItems[0].Index].Name;
 }

Upvotes: 1

Rikki
Rikki

Reputation: 3518

I'd suggest you to just check the data that you have in the "Items" property of the ListBox object and compare it with the "people" variable that you have. Be sure that they are not synchronized at the moment of firing "SelectedIndexChanged" event.

Hope it helps

Cheers

Upvotes: 0

Z .
Z .

Reputation: 12837

there is a short period of time when there is no item selected: just after the first one gets unselected and before the new one is selected. you should check in your code if there is an item selected before you do whatever you want to do with it.

Upvotes: 0

Related Questions