我有一个组合框来填充城市、州和 PinCode 的数据,这些组合框是下拉列表,用户会选择它。
并在表单打开后加载。
这是代码:
/// 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();
}
它有点大,我对所有组合框都执行相同的步骤,但是有没有一种方法可以以简单的方式合并它。