Tayyab Jatoi

Tayyab Jatoi

  • NA
  • 135
  • 27.8k

Wiring up Search button form includes Textbox and Combobox

Nov 13 2018 10:25 AM
 
I am trying to Wireup Search button my Form includes Textbox and combobox,but getting error when when trying to Search with ItemId.
Error: "The Connection was not closed.The Connections current state is open" 
 
Search button Code
 
private void searchButton_Click(object sender, EventArgs e)
{
string Id = ItemIdValue.Text;
string command = "Select * from Item where ItemId = " + Id;
cmd = new SqlCommand(command, con);
if (con.State != ConnectionState.Open)
{
con.Open();
}
SqlDataReader dr = cmd.ExecuteReader();
if (dr.Read())
{
categoryNameDropDown.Text = dr[1].ToString();
categoryIdValue.Text = dr[2].ToString();
itemNameValue.Text = dr[3].ToString();
companyNameValue.Text = dr[4].ToString();
productNameValue.Text = dr[5].ToString();
purchasePriceValue.Text = dr[6].ToString();
salePriceValue.Text = dr[7].ToString();
reorderLevelValue.Text = dr[8].ToString();
openingQuantityValue.Text = dr[9].ToString();
unitValue.Text = dr[10].ToString();
}
else
{
MessageBox.Show("Record is not Exist", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
Reset();
}
dr.Close();
con.Close();
}
CategoryName Combobox Code
private void categoryNameDropDown_SelectedIndexChanged(object sender, EventArgs e)
{
cmd = new SqlCommand("select * from ItemCategory where CategoryName = '"+categoryNameDropDown.Text+"'",con);
con.Open(); -----Error is coming on this line "The Connection was not closed.The Connections current state is open"
cmd.ExecuteNonQuery();
SqlDataReader dr;
dr = cmd.ExecuteReader();
while (dr.Read())
{
string CategoryId = (string)dr["CategoryId"].ToString();
categoryIdValue.Text = CategoryId;
}
con.Close();
}
 
 

Answers (9)