Let's look at the block of code in question
con2.Open();
OleDbCommand cmd2 = con2.CreateCommand();
cmd2.CommandType = CommandType.Text;
cmd2.CommandText = "select * from Table4 where MA='" + label2.Text + "'";
int v2 = cmd1.ExecuteNonQuery();
DataTable dt2 = new DataTable();
OleDbDataAdapter Da2 = new OleDbDataAdapter(cmd2);
Da2.Fill(dt2);
count2 = Convert.ToInt32(dt2.Rows.Count.ToString());
dataGridView2.DataSource = dt2;
con2.Close();
What happens if I put this value into
label2:
'; DROP TABLE Table4
Oh I know, that table could disappear due to this code being susceptible to SQL Injection
The proper way to do this would be to use parameters:
OleDbCommand cmd2 = con2.CreateCommand();
cmd2.CommandType = CommandType.Text;
cmd2.CommandText = "select * from Table4 where MA= ?";
cmd2.Parameters.AddWithValue("@label2", label2.Text);
As previously mentioned
int v2 = cmd1.ExecuteNonQuery();
Is most likely a typo. Also, this command is associated with Connection1 from the previous block of code and that connection was closed after this command was run earlier.
Even if this were corrected... it is a little inefficient. You are running the SELECT statement twice in each block, first as NonQuery to get the count and then again to do the data fill.
Did you realize that
count2 and
v2 ideally are the same value? And why the conversion from an Int to a String and back to an Int?
count2 = Convert.ToInt32(dt2.Rows.Count.ToString());