The parameterized query to the SQL-Server database does not work. For the current TreeView node, I pull the data from the related table.

private void treeView1_AfterSelect(object sender, TreeViewEventArgs e) { string cur = treeView1.SelectedNode.Text; string connectionString = @"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\TestBase.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True"; string commandText = "SELECT Employees.Name, Employees.Experience FROM Departments INNER JOIN Employees ON Departments.id=Employees.Department WHERE Departments.Name=" + cur + ";"; SqlConnection conn = new SqlConnection(); conn.ConnectionString = connectionString; conn.Open(); SqlDataAdapter dataAdapter = new SqlDataAdapter(commandText, conn); DataSet ds = new DataSet(); dataAdapter.Fill(ds); dataGridView1.DataSource = ds.Tables[0].DefaultView; } 

If I remove WHERE in the query, then everything works, but all the records are displayed, but I need only certain ones. On the line dataAdapter.Fill (ds), a SQLException exception is thrown: Invalid column name 'Accounting'.

    2 answers 2

    Correctly done through parameters and through SqlCommand:

     string commandText = "SELECT Employees.Name, Employees.Experience FROM Departments INNER JOIN Employees ON Departments.id=Employees.Department WHERE Departments.Name= @Name ;"; SqlCommand cmd = new SqlCommand(commandText, conn); SqlParameter Param1 = new SqlParameter(" @Name ", SqlDbType.VarChar); Param1.Value = cur; cmd.Parameters.Add(Param1); SqlDataAdapter dataAdapter = new SqlDataAdapter(cmd); 
    • The most appropriate overloaded method for "System.Data.SqlClient.SqlDataAdapter.SqlDataAdapter (string, string)" has several invalid arguments. He does not like the last line, although there is a method with these parameters - Pavel Voevod
    • Yes, the second parameter is superfluous, cmd is enough. - Yura Ivanov
    • By the way, the result is still the same - Pavel Voevoda
    • I unfortunately have no opportunity to check, but this is the right way. Specifying parameter values ​​in the query string is a vicious practice. - Yura Ivanov
    • Error: Fill: The SelectCommand.Connection property is not initialized. - Pavel Voevoda

    If the Departments.Name is a string, then you need to put "". Those. ...Departments.Name='" + cur + "';" . But it’s still better, as advised by Yura Ivanov. For example, it’s easier to set the date through parameters.