Home > Blockchain >  Search in the database
Search in the database

Time:05-18

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'.'

CodePudding user response:

What does the "search_name" parameter contains? The Message? The Column Name?

Your query is

Select * from MessagesTable where "   search_name   " = @From"

Then you specifies the "search_name" as a parameter for the @From... So I believe your input was "Name" and your query is looked like this now:

Select * from MessagesTable where Name = 'Name';

You do not have any Name column in this specified table as you described.

CodePudding user response:

You can change it as follows. Of course, if I understand correctly, that you want to search in the messages field by the input you get from the user.

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  MESSAGE = @From";
    cmd.Parameters.AddWithValue("@From", search_name);

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

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