How to load the SQL data into several ComboBox easily, am i doing the correctly or is there another way
Posted
by
Dominic Deepan.d
on Stack Overflow
See other posts from Stack Overflow
or by Dominic Deepan.d
Published on 2012-12-18T04:14:02Z
Indexed on
2012/12/18
5:03 UTC
Read the original article
Hit count: 186
I have a Combobox to fill the data for City, State and PinCode these combobox is dopdown list and the user will pick it.
and it loads once the form opens.
Here is the CODE:
/// CODE TO BRING A DATA FROM SQL INTO THE FORM DROP LIST
/// To fill the sates from States Table
cn = new SqlConnection(@"Data Source=Nick-PC\SQLEXPRESS;Initial Catalog=AutoDB;Integrated Security=True");
cmd= new SqlCommand("select * from TblState",cn);
cn.Open();
SqlDataReader dr;
try
{
dr = cmd.ExecuteReader();
while (dr.Read())
{
SelectState.Items.Add(dr["State"].ToString());
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
cn.Close();
}
//To fill the Cities from City Table
cn1 = new SqlConnection(@"Data Source=Nick-PC\SQLEXPRESS;Initial Catalog=AutoDB;Integrated Security=True");
cmd1 = new SqlCommand("SELECT * FROM TblCity", cn);
cn.Open();
SqlDataReader ds;
try
{
ds = cmd1.ExecuteReader();
while (ds.Read())
{
SelectCity.Items.Add(ds["City"].ToString());
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
cn1.Close();
}
// To fill the Data in the Pincode from the City Table
cn2 = new SqlConnection(@"Data Source=Nick-PC\SQLEXPRESS;Initial Catalog=AutoDB;Integrated Security=True");
cmd2 = new SqlCommand("SELECT (Pincode) FROM TblCity ", cn2);
cn2.Open();
SqlDataReader dm;
try
{
dm = cmd2.ExecuteReader();
while (dm.Read())
{
SelectPinCode.Items.Add(dm["Pincode"].ToString());
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
cn2.Close();
}
its kinda Big, i am doing the same steps for all the combo-box, but is there a way i can merge it in a simple way.
© Stack Overflow or respective owner