开发者

C# Windows Form html like dropdown menu

开发者 https://www.devze.com 2022-12-14 00:42 出处:网络
I am looking to create a dropdown menu in my windows form application that is similar to the dropdown menu in html i.e.etc..

I am looking to create a dropdown menu in my windows form application that is similar to the dropdown menu in html i.e. etc..

I need each entry to display text to user but store a value to be used in my app.

I a开发者_C百科m currently using a combobox but that doens't seem to let me store an associated value for each entry.

Thanks in advance.


You can store anything in a combo box, up to and including an object instance that holds the value you need, plus the string. All you need to do is override ToString in the class you use as item.

class Item {
    public string Name = "";
    public int Value = 0;

    public Item(string name, int value) {
        this.Name = name;
        this.Value = value;
    }

    public override string ToString() {
        return this.Name;
    }
}

Then:

        for (int i = 0; i < 10; i++) {
            Item item = new Item("Item no. " + i.ToString(), i);
            comboBox1.Items.Add(item);
        }

When you work with comboBox1.Items all you need to do is cast the items to Item and you're all set.


A ComboBox does let you store as many associated values as you want - just bind it to a collection of your objects (which can as many properties as you like), and use DisplayMember, ValueMember, and SelectedValue properties of the ComboBox to designate property that will provide text to be displayed, and property that will provide value for SelectedValue.

0

精彩评论

暂无评论...
验证码 换一张
取 消