17

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 use comboBox1.SelectedIndex = comboBox1.Items.IndexOf("something") but once I dynamically generate the contents of the comboboxes, I can't get it to work anymore.

This is how I fill my combo box (located in the class's constructor);

        string command = "SELECT category_id, name FROM CATEGORY ORDER BY name";
        List<string[]> list = database.Select(command, false);

        cbxCategory.Items.Clear();

        foreach (string[] result in list)
        {
            cbxCategory.Items.Add(new ComboBoxItem(result[1], result[0]));
        }

I can't seem to get it to work to set a default value, like if I place cbxCategory.SelectedIndex = cbxCategory.Items.IndexOf("New") below the above code, it won't work.

WinForms, by the way.

Thank you in advance.

Mark Hall
  • 53,938
  • 9
  • 94
  • 111
Roel
  • 754
  • 3
  • 13
  • 30
  • WPF? Winforms? Please specify it! In the tags, in the title or in the question. – Cédric Bignon Jan 29 '13 at 18:46
  • SelectedIndex should work fine. As the answers suggested, make sure that what you are looking for actually exists...otherwise I recommend using a fixed number rather than a search. – Nevyn Jan 29 '13 at 18:50
  • Sadly, a fixed number is not an option. I will run the debugs. – Roel Jan 29 '13 at 18:57
  • Do you have a debugger to check that the value is set to a valid index (i.e. not -1 etc)? If it is, you may simply need to call cbxCategory.Refresh() – 75inchpianist Jan 29 '13 at 18:49
  • could you share your `ComboBoxItem` class? – spajce Jan 30 '13 at 01:26

5 Answers5

24

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

iltzortz
  • 2,342
  • 2
  • 19
  • 35
  • I have no idea on what index my default item is going to be as the combobox is populated with data from the database. Therefor I have to use IndexOf (or something similar to match values). It works if I staticly add the items to the dropdown instead of loading them from the database - but whenever I load them from the database it doesn't work somehow. – Roel Jan 29 '13 at 18:50
  • after you load them set cbxCategory.SelectedIndex = 0; – iltzortz Jan 29 '13 at 18:59
1

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.

RogerN
  • 3,761
  • 11
  • 18
  • You are absolutely right. How would you recommend searching for it? – Roel Jan 29 '13 at 19:04
  • ComboBoxItem is not a class in the System.Windows.Forms namespace (are you sure this is WinForms?); since it appears to be custom class then I can't provide you with the exact search code because you haven't provided the property names. You're just going to have to iterate over the collection to find the correct item. Unfortunately ComboBox.ObjectCollection is not very LINQ-friendly. You could also just remember the index as you are initially adding items to the control. – RogerN Jan 29 '13 at 19:17
  • it seems that your explanation is not true. see my answer :) – spajce Jan 29 '13 at 23:11
1

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", "ddd" } };

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;
    }
}
kmatyaszek
  • 19,016
  • 9
  • 60
  • 65
0

Here's my simple solution

        var list = comboBox1.Items.Cast<string>().ToList();
        cbxCategory.SelectedIndex = list.FindIndex(c => c.StartsWith("test"));
spajce
  • 7,044
  • 5
  • 29
  • 44
  • This solution will cause an InvalidCastException because ComboBoxItem (presumably a custom class since it's not part of Windows Forms) cannot be cast as a string. – RogerN Jan 30 '13 at 00:51
  • yes, if the OP will provide his the `Custom ComboBox` it would be better `:D` since we're focus in default `ComboBox`. – spajce Jan 30 '13 at 01:23
0

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;