I have a combobox which is called combobox1
, which I want to populate it with id
as value and Name
as display name. I searched and read some tutorial and found this code to use in Form load event, but it doesn't populate the list. I see an empty dropdown. Any ideas of where I am wrong?
In my database class I have this function.
public static void FillDropDownList(string Query, System.Windows.Forms.ComboBox DropDownName)
{
SqlDataReader dr;
SqlConnection myConnection = new SqlConnection(CONNECTION_STRING);
try
{
myConnection.Open();
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
// Check whether the Drop Down has existing items. If YES, empty it.
if (DropDownName.Items.Count > 0)
DropDownName.Items.Clear();
SqlCommand cmd = new SqlCommand(Query, myConnection);
dr = cmd.ExecuteReader();
while (dr.Read())
DropDownName.Items.Add(dr[0].ToString());
Console.Write(DropDownName.Items.Add(dr[0].ToString()));
dr.Close();
}
In my form i call it as
private void sales_record_Load(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(DBUtils.CONNECTION_STRING);
DBUtils.FillDropDownList("select id,Name from Farms", comboBox1);
}