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

前端 未结 6 1009
南旧
南旧 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:25

    Using both the SelectedIndexChanged and SelectedValueChanged didn't work for me - the ListBox's SelectedValue property was always null. This surprised me, too.

    As a lame workaround, you could just pull the object out of the ListBox directly, using the SelectedIndex:

    public Form1()
    {
        InitializeComponent();
    
        this.listBox1.DisplayMember = "Name";
        this.listBox1.ValueMember = "ID";
    
        this.listBox1.Items.Add(new Test(1, "A"));
        this.listBox1.Items.Add(new Test(2, "B"));
        this.listBox1.Items.Add(new Test(3, "C"));
        this.listBox1.Items.Add(new Test(4, "D"));
        this.listBox1.Items.Add(new Test(5, "E"));
    }
    
    private void OnSelectedIndexChanged(object sender, EventArgs e)
    {
        if(-1 != this.listBox1.SelectedIndex)
        {
            Test t = this.listBox1.Items[this.listBox1.SelectedIndex] as Test;
            if(null != t)
            {
                this.textBox1.Text = t.Name;
            }
        }
    }
    

    (Test is just a simple class with two properties - ID and Name).

    It seems like there should be a better way, but if nothing else this should work.

提交回复
热议问题