1

I bind a ComboBox with a data source it shows the datasource in the dropdown but I want a default selected value.

Example:
"Select" is selected by default like shown in this picture.

In my Case result are show like this

This is my code:

public void BindComboBoxItem()
{
    try
    {
        ItemRepository repo = new ItemRepository();
        List<Item> items = repo.GetAll();
        cbxSelectItem.DataSource = items;
        cbxSelectItem.DisplayMember = "Name";
        cbxSelectItem.ValueMember = "Id";
    }
    catch (Exception ex)
    {
        MessageBox.Show(MessageResource.ErrorMessage, "Error",
                   MessageBoxButtons.OK, MessageBoxIcon.Error);
    }
}
EpicKip
  • 4,015
  • 1
  • 20
  • 37
M Tahir Latif
  • 11
  • 1
  • 2
  • 8

3 Answers3

1

If you want to have "Select" as your default selected value then you need to add it in your items and set

cbxSelectItem.SelectedIndex = //input the index of "Select" 

which is 0 in the case of your first image link.

P. Pat
  • 488
  • 4
  • 13
0

By setting the DropDownStyle the ComboBox always has a value selected. If you do not want this behavior you can only use the last line.

//This makes it so you have to select a value from the list, there is also 1 auto selected
comboBox.DropDownStyle = ComboBoxStyle.DropDownList;
//This makes sure we're selecting the value we want
comboBox.SelectedIndex = comboBox.Items.IndexOf( "value" );

If you want to add an item to tell people to select a value you can do this:

comboBox.Items.Insert(0, "Please select any value");

Note* this creates a selectable item, if you don't want this you can do this:

private void comboBox_TextChanged(object sender, EventArgs e)
{
    if(comboBox.SelectedIndex <= 0)
    { 
        comboBox.Text = "Please select a value";
    }
}

private void Form_Load(object sender, EventArgs e)
{
    comboBox.Text = "Please select a value";
}
EpicKip
  • 4,015
  • 1
  • 20
  • 37
0

It can be done using Key pair my code is here

  private void BindComboBoxItem()
    {
        ItemRepository repo = new ItemRepository();
        List<Item> items = repo.GetAll();
        List<KeyValuePair<int, string>> allitems = new List<KeyValuePair<int, string>>();
        KeyValuePair<int, string> first = new KeyValuePair<int, string>(0, "Please Select");
        allitems.Add(first);
        foreach (Item item in items)
        {
            KeyValuePair<int, string> obj = new KeyValuePair<int, string>(item.Id, item.Name);
            allitems.Add(obj);
        }
        cbxSelectItem.DataSource = allitems;
        cbxSelectItem.DisplayMember = "Value";
        cbxSelectItem.ValueMember = "Key";
    }
M Tahir Latif
  • 11
  • 1
  • 2
  • 8