public static void fill_combo(string table, ComboBox cmb, string columns)
{
ds = new DataSet();
try
{
conn.Open();
da = new SqlDataAdapter($"SELECT {columns} FROM [{table}]", conn);
da.Fill(ds, table);
cmb.DataSource = ds.Tables[table];
cmb.ValueMember = ds.Tables[table].Columns[0].ToString();
cmb.DisplayMember = ds.Tables[table].Columns[1].ToString();
cmb.SelectedItem = null;
cmb.Text = "Select...";
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error");
}
finally
{
if (conn != null)
{
conn.Close();
}
}
}
Hey guys. With the code above i'm trying to get results from database and bind them to a combobox, but i want the first item to be a random "Select..." that isn't in the database. Thanks in advance.
Option 1 - You can insert a DataRow
containing desired values to the DataTable
:
var connection = @"Your Connection String";
var command = "SELECT Column1, Column2 FROM Table1";
var dt = new DataTable();
using (var da = new SqlDataAdapter(command, connection))
da.Fill(dt);
var row = dt.NewRow();
row["Column1"] = DBNull.Value;
row["Column2"] = "Select an Item";
dt.Rows.InsertAt(row, 0);
this.comboBox1.DataSource = dt;
this.comboBox1.ValueMember = "Column1";
this.comboBox1.DisplayMember = "Column2";
Option 2 - Instead of adding null data to the DataTable
, you can set DropDownStyle
to DropDownList
and set its DrawMode
to OwnerDrawFixed
and handle DrawItem
event and draw the place holder when selected index is -1:
private void comboBox1_DrawItem(object sender, DrawItemEventArgs e)
{
var combo = sender as ComboBox;
var text = "Select an Item";
if (e.Index > -1)
text = combo.GetItemText(combo.Items[e.Index]);
e.DrawBackground();
TextRenderer.DrawText(e.Graphics, text, combo.Font,
e.Bounds, e.ForeColor, TextFormatFlags.Left);
}
To show the place holder, it's enough to set comboBox1.SelectedIndex = -1;