Search code examples
c#textboxtextchanged

Textbox with TextChanged event doesn't bring the date in second enter


I have a Textbox with TextChanged event working very well if I enter the correct id. But if I enter a wrong id and the MessageBox appears in catch section, and then I try to enter a correct id, it keeps giving me the MessageBox error.

Here is my code:

private void Pro1txt_onChange(object sender, EventArgs e)
{
    try
    {
        cmd1 = new SqlCommand(" SELECT  P_Name,P_Price,P_Quantity from Product where P_ID =  '" + Pro1txt.Text + "'", cn);
        cn.Open();
        DataReader = cmd1.ExecuteReader();
        DataReader.Read();
        ProdcutName1.Text = DataReader["P_Name"].ToString();
        UnitPrice1.Text = DataReader["P_Price"].ToString();
        Rem_Quantity1.Text = DataReader["P_Quantity"].ToString();

        if (Rem_Quantity1.Text =="0")
        {
            Req_Quantity1.Enabled = false;
        }             
    }
    catch
    {
        MessageBox.Show("Error","danget",MessageBoxButtons.OK,MessageBoxIcon.Hand);             
    }
}

Solution

  • You query is vulnerable to SQL Injection. You should use Parameters

    For example:

    cmd1 = new SqlCommand(" SELECT  P_Name,P_Price,P_Quantity from Product where P_ID =  @id", cn);
    cmd1.Parameters.Clear();
    cmd1.Parameters.Add("@id", SqlDbType.Int).Value = int.Parse(Pro1txt.Text);
    cn.Open();
    ....
    

    and try not to include messagebox in your catch block.. use finally to close your DB connection.

    Search for query with parameters for more info.