1

I want to implement a search method in which the user can select the search type from a combobox and enter search value in textbox.

The search button code is here but when I click on the search button, result datagridview is empty.

What is the problem?

 private void button1_Click(object sender, EventArgs e)
 {
     SqlCommand cmd = new SqlCommand();

     SqlConnection con = new SqlConnection();
     con.ConnectionString = "Data Source=.;Initial Catalog=MyDatabase;Integrated Security=True";

     con.Open();

     cmd.Connection = con;

     DataSet ds = new DataSet();

     SqlDataAdapter da = new SqlDataAdapter();

     cmd.CommandText = "select * from person where @parameter1=@parameter";

     if (comboBox1.SelectedIndex == 0)
     {
        cmd.Parameters.AddWithValue("@parameter1", "name");
     }
     else
     {
        cmd.Parameters.AddWithValue("@parameter1", "code");
     }

     cmd.Parameters.AddWithValue("@parameter",textBox1.Text);

     da.SelectCommand = cmd;
     da.Fill(ds);

     dataGridView1.DataSource = ds.Tables[0];
     con.Close();
}
2
  • Why don't you use EF? Just wondering, would be a lot easier. Commented Jul 20, 2015 at 14:50
  • You cannot parametrize object identifiers like field names Commented Jul 20, 2015 at 14:51

1 Answer 1

1

You can't parameterize column names unless you take extra consideration like with dynamic SQL (not recommended in this situation).

What you should do is change your logic and query to handle NULL for name or text, or just have conditional logic to construct your query.

string colSearchName;

if (comboBox1.SelectedIndex == 0)
    colSearchName = "name";
else
    colSearchName = "code";

cmd.CommandText = string.Format("select * from person where {0}=@parameter", colSearchName);

// ... so on and so forth
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.