简体   繁体   中英

ListBox get selected index?

I try to get index of selected item in ListBox:

private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
  int index = listBox1.SelectedIndex;
}

When I select the second item it returns me index zero again.

Filling ListBox:

private void fillWorkListBox()
{
  this.list = manager.works();
  this.listBox1.DisplayMember = "name";
  this.listBox1.ValueMember = "id";

  for (var i = 0; i < this.list.works.Count; i++)
  {
      string name = "№" + this.list.works[i].id + " - " + this.list.works[i].name;

      WorkModel work = new WorkModel();
      work.name = name;
      work.id = this.list.works[i].id;

      listBox1.Items.Add(work);
  }
}

It seems that your listbox has the SelectionMode property set to something different from the default. For example if the SelectionMode is MultipleSimple then you cannot use the SelectedIndex property because it is not a list of the elements selected. Instead you use the SelectedIndices collection

void listBox1_SelectedIndexChanged(object sender, EventArgs args)
{
    foreach(int x in listBox1.SelectedIndices)
        Console.WriteLine(x);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM