Here is an example using a ComboBox and a TextBox. I've used a ComboBox with fixed entries for the user to choose from. I don't want them to enter the column name for a few reasons: They might misspell it, they might introduce other errors and because I'm using string concatenation to get the column name (only the name, NOT the value) it provides a further protection against SQL Injection.
private void button1\_Click(object sender, EventArgs e)
{
if (cmbColumns.SelectedIndex == -1)
{
MessageBox.Show("You must select a column");
return;
}
if (string.IsNullOrEmpty(tbSearch.Text))
{
MessageBox.Show("You must enter a value to search for");
return;
}
// This bit would NOT normally be within the UI layer
var conString = ConfigurationManager.ConnectionStrings\["ConnectToDB"\].ConnectionString;
using (SqlConnection conn = new SqlConnection(conString))
{
conn.Open();
using (var myCommand = new SqlCommand())
{
myCommand.Connection = conn;
var sb = new StringBuilder(
"SELECT First\_Name, Last\_Name, Grid\_Square, Country, State, Call\_Sign, Date\_Time, Mode, Power ");
sb.Append("FROM clouddata WHERE ");
sb.Append(cmbColumns.SelectedItem);
sb.Append("=@searchValue");
myCommand.CommandText = sb.ToString();
myCommand.Parameters.AddWithValue("@searchValue", tbSearch.Text);
using (var adapter = new SqlDataAdapter(myCommand))
{
var myTable = new DataTable();
adapter.Fill(myTable);
dataGridView1.DataSource = myTable;
}
}
}
}