samedi 9 mai 2015

declare scalar variable exception while populating datagridview with data from ms sql

I am trying to put data from an sql query into 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?

Aucun commentaire:

Enregistrer un commentaire