Myworld Myworld - 3 months ago 41
C# Question

add an item to combobox before bind data from data base

I had combobox in windows form which retrive data from data base I did this well but I want to add first item <-Please select Category-> befor the data from data base .How can I do that? and where can I put it ?

public Category()
{
InitializeComponent();
CategoryParent();

}
private void CategoryParent()
{

using (SqlConnection Con = GetConnection())
{

SqlDataAdapter da = new SqlDataAdapter("Select Category.Category ,Category.Id from Category", Con);
DataTable dt = new DataTable();
da.Fill(dt);
CBParent.DataSource = dt;
CBParent.DisplayMember = "Category";
CBParent.ValueMember = "Id";
}
}

Answer

You could either add the default text to the Text property of the combobox like this (preferred):

CBParent.Text = "<-Please select Category->";

Or, you could add the value to the datatable directly:

da.Fill(dt);
DataRow row = dt.NewRow();
row["Category"] = "<-Please select Category->";
dt.Rows.InsertAt(row, 0);
CBParent.DataSource = dt;
Comments