0
            temp = textBox3.Text;
            query6 = "SELECT DISTINCT Weight_Box FROM MO_spec WHERE PC = '1508-527-00' ";
            SqlCommand cmd6 = new SqlCommand(query6, con5);
            SqlDataReader dr1 = cmd6.ExecuteReader();
             if (dr1.Read())
             {    w1 = (float)dr1["Weight_Box"];
                 float a1 = (float)Convert.ToDouble(textBox5.Text);
                 bool valid1 = float.TryParse(textBox5.Text.ToString(), out a1);
                 nw1 = w1 * a1;
                 query13 = "insert into intern_planuser(DocCode,DocDate,VenderName,Licenseplate,DriverName,OrderItem,ProductCode,WeightPerUnit,Amount,NetWeight) values('" + label17.Text + "','" + label3.Text + "','" + comboBox1.Text + "','" + comboBox2.Text + "','" + comboBox3.Text + "','" + textBox1.Text + "','" + textBox3.Text + "',w1,a1,nw1";
                 SqlCommand cmd13 = new SqlCommand(query13, con5);
                 cmd13.Connection.Open();
                 cmd13.ExecuteNonQuery();
                 cmd13.Connection.Close();
                 MessageBox.Show("saved");
             }
             else
             {
                 MessageBox.Show("Please enter PC in the corect form OR cannot retrive data from database");
                 textBox3.Focus();
             } 

How can I use the text box as a value in SQL statement. I try to change '1508-527-00' to "+textbox3.text+" or a value as a "+temp+" i try that but it got an error the datatype in the table is varchar.

wanna
  • 15
  • 3
  • 3
    Use SQL parameters...https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.parameters(v=vs.110).aspx – apomene Jul 02 '18 at 07:47

1 Answers1

0

The correct way to write your query using the values typed by your user is the following

bool valid1 = false;
query6 = "SELECT DISTINCT Weight_Box FROM MO_spec WHERE PC = @pc";
using(SqlCommand cmd6 = new SqlCommand(query6, con5)))
{
    cmd6.Parameters.Add("@pc", SqlDbType.VarChar).Value = textBox1.Text;
    using(SqlDataReader dr1 = cmd6.ExecuteReader())
    {
         if(dr1.Read())
         {
             w1 = Convert.ToSingle(dr1["Weight_Box"]);
             valid1 = float.TryParse(textBox5.Text, out a1);
         }
    } 
    // Closing the reader here allows the following query without
    // MultipleActiveRecordset active in your connectionstring
    if(valid1)
    {
         // the remainder of your code goes here.
         // Inside proper using blocks and with the correct parameters
    }

}

Of course this should be also used for your insert query. Always use parameters when you want to pass values to your database and do not concatenate your sql command with the user input. This leads to parsing problems (what if the input contains a single quote?) or worse to SQL Injection

Steve
  • 213,761
  • 22
  • 232
  • 286
  • 1
    can i ask more about that after dr1 how can i bring the value to variable for calculate – wanna Jul 02 '18 at 07:59