Make ListBox items have a different value than item text

前端 未结 5 1603
旧时难觅i
旧时难觅i 2020-12-08 21:18

I want a ListBox full of items. Although, each item should have a different value. So when the user selects an item and presses a button, a method will be calle

5条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-08 21:55

    You can choose what do display using the DisplayMember of the ListBox.

    List data = new List();
    data.Add(new SomeData() { Value = 1, Text= "Some Text"});
    data.Add(new SomeData() { Value = 2, Text = "Some Other Text"});
    listBox1.DisplayMember = "Text";
    listBox1.DataSource = data;
    

    When the user selects an item, you can read the value (or any other property) from the selected object:

    int value = (listBox1.SelectedItem as SomeData).Value;
    

    Update: note that DisplayMember works only with properties, not with fields, so you need to alter your class a bit:

    public class SomeData
    {
        public string Value { get; set; };
        public string Text { get; set; };
    }
    

提交回复
热议问题