It's ok, it works. But ... connections and commands are scarce resources and should be Disposed when you have finished with them. The easiest way is to use a
using
block:
public void Needform()
{
string mainconn = ConfigurationManager.ConnectionStrings["MY"].ConnectionString;
using (SqlConnection sqlconn = new SqlConnection(mainconn))
{
sqlconn.Open();
string sqlquery = "SELECT * FROM [dbo].[Governorate]";
using (SqlCommand sqlcomm = new SqlCommand(sqlquery, sqlconn))
{
using (SqlDataAdapter sda = new SqlDataAdapter(sqlcomm))
{
DataTable dt = new DataTable();
sda.Fill(dt);
comboBoxGovernorate.ValueMember = "id_Governorate";
comboBoxGovernorate.DisplayMember = "name";
comboBoxGovernorate.DataSource = dt;
comboBoxCity.Enabled = false;
}
}
}
}
private void ComboBoxGovernorate_SelectedIndexChanged(object sender, EventArgs e)
{
if (comboBoxGovernorate.SelectedValue.ToString() != null)
{
string mainconn = ConfigurationManager.ConnectionStrings["MY"].ConnectionString;
using (SqlConnection sqlconn = new SqlConnection(mainconn))
{
sqlconn.Open();
string sqlquery = "SELECT * FROM [dbo].[City] WHERE id_Governorate=@id_Governorate";
using (SqlCommand sqlcomm = new SqlCommand(sqlquery, sqlconn))
{
sqlcomm.Parameters.AddWithValue("@id_Governorate", comboBoxGovernorate.SelectedValue.ToString());
using (SqlDataAdapter sda = new SqlDataAdapter(sqlcomm))
{
DataTable dt = new DataTable();
sda.Fill(dt);
comboBoxCity.ValueMember = "id";
comboBoxCity.DisplayMember = "city";
comboBoxCity.DataSource = dt;
comboBoxCity.Enabled = true;
}
}
}
}
}
There are two other changes I'd recommend:
1) Just a "style" thing, but use UPPERCASE for SQL keywords - it makes it easier to "find" them in a command.
2) Don't do "SELECT * FROM" at all - always name the columns you need to fetch. That way, you don't waste bandwidth fetching data you aren't going to use (and if you add images for example that can be significant), and it helps "protect" you from DB layout changes since you control the order in which they are returned. With tables for example, that can make a big difference to your app when you update things later.