baban jamal baban jamal - 1 month ago 6
C# Question

How to search over whole cities in combobox

I inserted about 18 cities in government field and I can search over each city I want by ID, but now I want to search over all of the cities by ID when I do not select any thing in combobox.

string c = "%";
c = comboBox1.Text;
int a;
a = Convert.ToInt32(textBox1.Text);
a = int.Parse(textBox1.Text);
SqlCommand cmd = new SqlCommand("select * from Person where ( PER_ID = '" + a + "' and GOV_NAME_AR = '" + c + "') ", con);
cmd.CommandTimeout = 600;
con.Open();
SqlDataReader rdr = cmd.ExecuteReader();
if (rdr.HasRows)
{
// MessageBox.Show("Successfully found Data");
// SqlDataReader DR = cmd.ExecuteReader();
BindingSource source = new BindingSource();
dataGridView1.DataSource = source;
}
else
{
MessageBox.Show("data not found");
}
con.Close();

Answer

You could change the statement in case of "nothing selected"

if (ComboBox.Text == string.Empty)
{   
    cmd.CommandText = "select * from Person where ( PER_ID = '" + a + "')";
}

Remarks:

  • use variable names like string sCity = "%"; instead of string c = "%";
  • use parameters for your sql statements where ( PER_ID = @Person) and cmd.Parameters.Add("@Person", SqlDbType.Int32).Value = int.Parse(textBox1.Text);