Sir, I need your help in solving a doubt in Windows Form Application.
Please go through the code below. Data is being rendering from database.
I want to insert "-Select-" to the Zero index of the comboBox.
How can it possible?
try
{
if(sqlCon.State==ConnectionState.Closed)
{
sqlCon.Open()
}
DataTable dtbl=new DataTable();
SqlDataAdapter Sqlda=new SqlDataAdapter("StudentViewAll", sqlCon);
da.Fill(d);
combBox1.DataSource = dtbl;
comboBox1.DisplayMember="Name";
comboBox1.ValueMember="id;
}
catch(Exception)
{
throw;
}
Loading

VulpesPosted Oct 5, 2013, 9:10 AM
try
{
if(sqlCon.State==ConnectionState.Closed)
{
sqlCon.Open()
}
SqlDataAdapter Sqlda=new SqlDataAdapter("StudentViewAll", sqlCon);
da.Fill(d); // it's assumed 'd' is a DataSet
DataTable dtbl = d.Tables[0]; // get first or only table
DataRow dr = dtbl.NewRow();
dr["Name"] = "-Select-";
dr["id"] = 0; // say
dtbl.Rows.InsertAt(dr, 0); // insert at index 0
combBox1.DataSource = dtbl;
comboBox1.DisplayMember="Name";
comboBox1.ValueMember="id";
}
catch(Exception)
{
throw;
}
And, if you want to prevent the user from selecting the inserted row, you can handle the combobox's SelectedIndexChanged event as follows:
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if (comboBox1.SelectedIndex == 0) comboBox1.SelectedIndex = 1;
}