简体   繁体   中英

Declare scalar variable exception while populating DataGridview with data from SQL Server

I am trying to put data from a SQL query into a DataGridview, but when I try to run the program I am getting the exception

must declare scalar variable @cathedra

Here is the code:

string connectionString = "user id=bogdan_db; password=1234;server=localhost; Trusted_Connection=yes; database=cafedrascience; connection timeout=30";
string sql = @"select *
               from researc r inner join research_cafadra rc on r.id = rc.researc_id
                    inner join cathedra c on c.id = rc.cafadre_id
               where c.name like @Cathedra;";

using (var connection = new SqlConnection(connectionString))
    using (var command = new SqlCommand(sql, connection))
    {
        command.Parameters.Add("@Cathedra", SqlDbType.VarChar, 50).Value = comboBox1.Text.ToString();
        connection.Open();
        command.ExecuteNonQuery();
        SqlDataAdapter dataAdapter = new SqlDataAdapter(sql, connectionString); //c.con is the connection string
        DataTable table = new DataTable();
        SqlCommandBuilder commandBuilder = new SqlCommandBuilder(dataAdapter);
        DataSet ds = new DataSet();
        dataAdapter.Fill(ds);
        dataGridView1.ReadOnly = true;
        dataGridView1.DataSource = ds.Tables[0];

Where I am mistaking?

The problem is that you're executing the query twice (and also connecting to the database twice). Please delete command.ExecuteNonQuery() and change

SqlDataAdapter dataAdapter = new SqlDataAdapter(sql, connectionString);

to

SqlDataAdapter dataAdapter = new SqlDataAdapter(command);

You're adding the parameter to command , which would be correct if you were actually using command . You're not... you call ExecuteNonQuery() and do nothing else with it.

You can remove these lines:

command.Parameters.Add("@Cathedra", SqlDbType.VarChar, 50).Value = comboBox1.Text.ToString();
command.ExecuteNonQuery();

And add this one after creating dataAdapter :

dataAdapter.SelectCommand.Parameters.Add("@Cathedra", SqlDbType.VarChar, 50).Value = comboBox1.Text;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM