1

I was trying to add a default value ("--select item--") in existing ComboBox which is getting filled by Database table. Here is my code.

SqlConnection conn = new SqlConnection("Server = .\\SQLEXPRESS; Initial Catalog= Student; Trusted_Connection = True");
string query = "select Id, Name from abc1";
SqlDataAdapter da = new SqlDataAdapter();
conn.Open();
DataTable dt = new DataTable();

SqlCommand command = new SqlCommand(query, conn);

SqlDataReader reader = command.ExecuteReader();

dt.Load(reader);

comboBox1.DataSource = dt;
comboBox1.ValueMember = "Id";
comboBox1.DisplayMember = "Name";      

Everything is working fine in above code and I'm getting CB filled with desired values.

Now when I try to insert default value using below, then it is throwing an error. This way was tried here

comboBox1.Items.Insert(0, "Select"); //this is throwing an error
comboBox1.SelectedIndex = 0;

enter image description here

I further explored below code to add default item.

comboBox1.SelectedIndex = -1;
comboBox1.Text = "Select an item";

This added an item as desired, but on any event, CB loses this value. After SelectIndexChanged event, I lose this value. So this cannot be my solution.

Any advise?

Community
  • 1
  • 1
Amnesh Goel
  • 2,617
  • 3
  • 28
  • 47

4 Answers4

2

I'd rather not intefere into binding, but edit SQL instead:

string query = 
  @"select 0 as Id,        -- or whatever default value you want
           'select' as Name, 
           0, 
     union all
    -- your original query here
    select Id, 
           Name,
           1  
      from abc1
    -- to have default value on the top
  order by 3 asc";
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
0

Insert's second parameter is expecting a ComboBox.ObjectCollection object. Try doing this:

Having a class

public class ComboboxItem
{
    public string Text { get; set; }
    public object Value { get; set; }
}

And using:

// This could be inline, but for simplicity step by step...
ComboboxItem item = new ComboboxItem();
item.Text = "Item text1";
item.Value = 12;

comboBox1.Items.Add(item);
//or
comboBox1.Items.Insert(0, item);
DDan
  • 8,068
  • 5
  • 33
  • 52
  • Nopes, no error.. Executed successfully. But didn't get the item as desired... CB is showing value that were in the DB only.. – Amnesh Goel Sep 14 '15 at 06:58
0

You can add programmatically the item to the datatable

DataRow dr = dt.NewRow();
dr["id"] = "0";
dr["name"] = "Select";

dt.Rows.InsertAt(dr, 0);

then you can set the datasource

comboBox1.DataSource = dt;
user3401335
  • 2,335
  • 2
  • 19
  • 32
0

If you just want to show a suggestion text to your user, the "EDIT" part of this answer may help (can only work if your ComboBox's DropDownStyle is not set to DropDownList).

But if you really want some "Select" item in your ComboBox, try this:

    void Form1_Load(object sender, EventArgs e)
    {
        //load your datatable here
        comboBox1.ValueMember = "ID";
        comboBox1.DisplayMember = "Name";
        comboBox1.Items.Add(new { ID = 0, Name = "Select" });
        foreach (DataRow a in dt.Rows)
            comboBox1.Items.Add(new { ID = a["ID"], Name = a["Name"] });
        comboBox1.SelectedIndex = 0;
        comboBox1.DropDown += new EventHandler(comboBox1_DropDown);
        comboBox1.DropDownClosed += new EventHandler(comboBox1_DropDownClosed);
    }

    void comboBox1_DropDownClosed(object sender, EventArgs e)
    {
        if (!comboBox1.Items.Contains(new { ID = 0, Name = "Select" }))
        {
            comboBox1.Items.Insert(0, new { ID = 0, Name = "Select" });
            comboBox1.SelectedIndex = 0;
        }
    }

    void comboBox1_DropDown(object sender, EventArgs e)
    {
        if (comboBox1.Items.Contains(new { ID = 0, Name = "Select" }))
            comboBox1.Items.Remove(new { ID = 0, Name = "Select" });
    }
Community
  • 1
  • 1
Nam Bình
  • 412
  • 2
  • 13
  • Isn't this so lengthy sol? – Amnesh Goel Sep 14 '15 at 07:37
  • Yep, if you don't mind having the "Select" item shown in dropdownlist, just replace `comboBox1.DataSource = dt;` with `comboBox1.Items.Add(new { ID = 0, Name = "Select" }); foreach (DataRow a in dt.Rows) comboBox1.Items.Add(new { ID = a["ID"], Name = a["Name"] });` – Nam Bình Sep 14 '15 at 07:40
  • Or just Add a new row on top of your datatable before set the ComboBox's DataSource as @user3401335 suggest. – Nam Bình Sep 14 '15 at 07:43