How to Set default combobox

前端 未结 5 1638
梦谈多话
梦谈多话 2021-02-19 00:48

So I\'ve been looking to set a default value for my combobox. I found a few things but none of them seem to work.

Actually, it works if I create a simple combobox and us

5条回答
  •  逝去的感伤
    2021-02-19 01:17

    You can use LINQ.

    //string command = "SELECT category_id, name FROM CATEGORY ORDER BY name";
    //List list = database.Select(command, false);
    // sample data...
    List list = new List { new string[] { "aaa", "bbb" }, new string[] { "ccc", "ffffd" } };
    
    cbxCategory.Items.Clear();
    
    foreach (string[] result in list)
    {
        cbxCategory.Items.Add(new ComboBoxItem(result[1], result[0]));
    }
    
    ComboBoxItem tmp = cbxCategory.Items.OfType().Where(x => x.ResultFirst == "bbb").FirstOrDefault();
    if (tmp != null)
        cbxCategory.SelectedIndex = cbxCategory.Items.IndexOf(tmp);
    

    ComboBoxItem class:

    class ComboBoxItem
    {
        public string ResultFirst { get; set; }
        public string ResultSecond { get; set; }
    
        public ComboBoxItem(string first, string second)
        {
            ResultFirst = first;
            ResultSecond = second;
        }
    }
    

提交回复
热议问题