Default combobox first item mixed with database results

[亡魂溺海] 提交于 2019-12-22 18:49:08

问题


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.


回答1:


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;



来源:https://stackoverflow.com/questions/40568907/default-combobox-first-item-mixed-with-database-results

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!