I’m making a program in visual C# where I’m pulling data and putting it into a dataGridView. This is all fine and dandy but if I attempt to pull more data afterwards (data I want to put into a textBox), it comes out with an error.
Here is the part where I’m pulling data and putting it into a dataGridView:
SqlConnection connect;
DataSet ds1 = new DataSet();
SqlDataAdapter da;
connect = new SqlConnection();
connect.ConnectionString = "Data Source=THEPC-PC\\SQLExpress;Initial Catalog=DataBase;Integrated Security=True";
string sql = "SELECT * FROM table WHERE column = '" + comboBox.Text + "'";
da = new SqlDataAdapter(sql, connect);
da.Fill(ds1, "table");
the_data_dataGridView.AutoGenerateColumns = false;
the_data_dataGridView.DataSource = ds1.Tables["table"];
connect.Open();
connect.Close();
The following code is the next query I’m trying to make just after the previous one. And it shows this error in the 3rd line where it says “ExecuteScalar”:
‘string’ does not contain a definition for ‘ExecuteScalar’ and no
extension method ‘ExecuteScalar’ accepting a first argument of type
‘string’ could be found (are you missing a using directive or an
assembly reference?)
SqlCommand sql2 = new SqlCommand("SELECT COUNT(column) FROM table WHERE column = '" + comboBox.Text + "'", connect);
connect.Open();
int the_result = System.Convert.ToInt32(sql.ExecuteScalar());
the_result_textBox.Text = the_result.ToString();
connect.Close();
Both pieces of code work fine in separate forms. But obviously won’t work one after the other. Now I’m sure I’m doing something really stupid here but can’t quite figure it out.
Thats because sql is a type string. You declare it as such in the first example.
You want to call ExecuteScalar on sql2 I think.