How to create a drop down menu in WinForms and C#

前端 未结 5 815
庸人自扰
庸人自扰 2020-12-16 15:40

I am new to using Visual Studio/WinForms/C#

I am trying to create a simple drop down menu where each item can have a value and a label.

This is what I would do

5条回答
  •  一整个雨季
    2020-12-16 16:00

    You need to set a datasource for your Combobox, it's better if you create a class and pass a list of Objects, for example:

    private void Init()
    {
        List items = new List();
        items.Add(new Item() { Text = "displayText1", Value = "ValueText1" });
        items.Add(new Item() { Text = "displayText2", Value = "ValueText2" });
        items.Add(new Item() { Text = "displayText3", Value = "ValueText3" });
    
        comboBox1.DataSource = items;
        comboBox1.DisplayMember = "Text";
        comboBox1.ValueMember = "Value";
    
    }
    
    public class Item
    {
        public Item() { }
    
        public string Value { set; get; }
        public string Text { set; get; }
    }
    

    Put the Init() method in your FormName_Load(object sender, EventArgs e){}.

提交回复
热议问题