How do I get at the listbox item's “key” in c# winforms app?

前端 未结 6 1000
南旧
南旧 2020-12-20 20:49

I am writing a winforms app in which a user selects an item from a listbox and edits some data that forms part of an associated object. The edits are then applied from the o

6条回答
  •  再見小時候
    2020-12-20 21:07

    Try grabbing the "ValueMember" from within the ListBox1_SelectedValueChanged event.

    private void ListBox1_SelectedValueChanged(object sender, EventArgs e)
    {
        if (ListBox1.SelectedIndex != -1)
        {
            string orbit = ListBox1.SelectedValue.ToString();
        }
    }
    
    ArrayList planets = new ArrayList();
    planets.Add(new Planet("Mercury", "1"));
    planets.Add(new Planet("Venus", "2"));
    
    //Remember to set the Datasource
    ListBox1.DataSource = planets;
    //Name and Orbit are properties of the 'Planet' class
    ListBox1.DisplayMember = "Name";
    ListBox1.ValueMember = "Orbit";
    

提交回复
热议问题