I would use ExecuteScalar to be more efficient... like this:
private void btnNext_Click(object sender, EventArgs e)
{
if (comboBox1.SelectedIndex == -1) return;
using (var conn = new SqlConnection(connstring))
{
conn.Open();
var cmd = new SqlCommand
{
CommandText = "select count(*) from dbtable where UPPER([name])=@name",
Connection = conn
};
cmd.Parameters.AddWithValue("@name", comboBox1.SelectedItem.ToString());
var res = (int)cmd.ExecuteScalar();
if (res > 0)
MessageBox.Show("exist");
}
}
Things to note:
- I've used
using
see
Establishing the Connection[
^]
Quote:
The Using block in Visual Basic or C# automatically disposes of the connection when the code exits the block, even in the case of an unhandled exception.
- I've used the ExecuteScalar method as it requires less code and fewer resources - see
SqlCommand.ExecuteScalar Method (System.Data.SqlClient)[
^]
- I check to ensure there is something actually selected on the comboBox before attempting to use the value.