Good day.
I am working on a Database app (Windows forms, C#).
My application has an option (i wish) to search by different parameters.
First search parameter/criteria is determined by a button click. When a button (for example "button1") is clicked, "label4" is assigned a value (different value for a different button; there are 6 buttons). This value is equal to the column name in my Database Table.
Also, after button1 is clicked a combobox ("comboBox1") is populated with data. [For defining query parameters (from comboBox selection) I used: Stackoverflow_1 and Stackoverflow_2.]
So, I tried to use the same principle as I got from 1 and 2, but it doesn't seem to work.
The results should be displayed in a "Data Grid View" after "button9 is clicked". Did I go wrong with "data adapter" and "data set" for the Data Grid View? If I "hard-code" the column value, it works, so my suspect is "column variable".
Help. Thank you.
TLDR: how to set variables in SQL string search?
public void button9_Click(object sender, EventArgs e)
{
if (con.State == ConnectionState.Closed)
{
con.Open();
string column = this.label4.Text; //column is the variable/value which I get when selecting "sort by" button
string XXX = this.comboBox1.GetItemText(this.comboBox1.SelectedItem); //XXX is the variable/value which I get when comboBox item is selected
SqlCommand cmd9 = new SqlCommand("SELECT * FROM tblTable WHERE @column=@XXX", con);
cmd9.Parameters.Add("@column", SqlDbType.NVarChar, -1);
cmd9.Parameters["@column"].Value = column;
cmd9.Parameters.Add("@XXX", SqlDbType.NVarChar, -1);
cmd9.Parameters["@XXX"].Value = XXX;
SqlDataAdapter adapter9 = new SqlDataAdapter(cmd9); //to view data in DataGridview I need a "data adapter" and "data set"
DataSet ds9 = new DataSet();
adapter9.Fill(ds9, "tblTable");
dataGridView1.DataSource = ds9.Tables["tblTable"];
con.Close();
}
}