Skip to content
Advertisement

Search in the database

This Messages form display table with these informations (ID,FROM,TO,TITLE,MESSAGE).

I am trying to search for all the messages send to a certain user . user will enter his name in the Search_textBox then it will filter the table to keep only messages to this user.

private void Search_button_Click(object sender, EventArgs e)
        {

        SqlCommand cmd = new SqlCommand();
        cmd.Connection = con;
        cmd.CommandType = CommandType.Text;
        cmd.CommandText = cmd.CommandText = "Select * from MessagesTable where To =" + Search_textBox.Text;
        cmd.Parameters.AddWithValue("@To", Search_textBox.Text);

        DataSet dataSet = new DataSet();
        SqlDataAdapter adapter = new SqlDataAdapter(cmd);
        adapter.Fill(dataSet);

        dataGridView1.DataSource = dataSet.Tables[0];
      
      
    }

I get this error :

System.Data.SqlClient.SqlException: 'Invalid column name 'To'.'

Advertisement

Answer

this is Correct

private void Search_button_Click(object sender, EventArgs e)
    {

    SqlCommand cmd = new SqlCommand();
    cmd.Connection = con;
    cmd.CommandType = CommandType.Text;
    cmd.CommandText = "Select * from MessagesTable where  [To]= @To";
    cmd.Parameters.AddWithValue("@To", Search_textBox.Text);

    DataSet dataSet = new DataSet();
    SqlDataAdapter adapter = new SqlDataAdapter(cmd);
    adapter.Fill(dataSet);

    dataGridView1.DataSource = dataSet.Tables[0];
  
  
}
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement