How to Set default combobox

前端 未结 5 1655
梦谈多话
梦谈多话 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 00:59

    It looks like you're searching the cbxCategory.Items collection for a string, but it contains items of type ComboBoxItem. Therefore the search will return -1.

    0 讨论(0)
  • 2021-02-19 01:09

    cbxCategory.SelectedIndex should be set to an integer from 0 to Items.Count-1 like

    cbxCategory.SelectedIndex  = 2;
    

    your

     cbxCategory.SelectedIndex = cbxCategory.Items.IndexOf("New") 
    

    should return -1 as long as no ComboboxItem mutches the string ("New");

    another solution though i don't like it much would be

    foreach(object obj in cbxCategory.Items){ 
        String[2] objArray = (String[])obj ;
        if(objArray[1] == "New"){
           cbxCategory.SelectedItem = obj;
           break; 
        }
    }
    

    perhaps this also requires the following transformation to your code

        foreach (string[] result in list)
        {
          cbxCategory.Items.Add(result);
        }
    

    I haven't tested the code and i am not sure about the casting to String[2] but something similar should work

    0 讨论(0)
  • 2021-02-19 01:16

    Here's my simple solution

            var list = comboBox1.Items.Cast<string>().ToList();
            cbxCategory.SelectedIndex = list.FindIndex(c => c.StartsWith("test"));
    
    0 讨论(0)
  • 2021-02-19 01:17

    You can use LINQ.

    //string command = "SELECT category_id, name FROM CATEGORY ORDER BY name";
    //List<string[]> list = database.Select(command, false);
    // sample data...
    List<string[]> list = new List<string[]> { 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<ComboBoxItem>().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;
        }
    }
    
    0 讨论(0)
  • 2021-02-19 01:23

    My solution:

    int? defaultID = null;
    foreach (DataRow dr in dataSource.Tables["DataTableName"].Rows)
    {
         if ((dr["Name"] != DBNull.Value) && ((string)dr["Name"] == "Default Name"))
         {
              defaultID = (int)dr["ID"];
         }
    }
    if (defaultID != null) comboBox.SelectedValue = defaultID;
    
    0 讨论(0)
提交回复
热议问题