I am trying To get ID against selected name in Drop Down list by using select query but it always returns the value "-1" instead of relevant result.
SqlCommand cmd2 = con.CreateCommand();
cmd2.CommandType = CommandType.Text;
cmd2.CommandText = "Select Pid From Provinces where Pname = '" + pr + "'";
cmd2.CommandText = "Select Pid From Provinces where Pname = '" + prov.Text + "'";
int pid = cmd2.ExecuteNonQuery();
You need to use ExecuteScalar instead of ExecuteNonQuery
int pid = Convert.ToInt32(cmd2.ExecuteScalar());
For more details please refer Link
The reason is that ExecuteNonQuery doesn't return the database value when using a Select command - It returns a return code for success or failure.
If you want to read the database value, use the following code. Note that I used an SqlParameter instead of your parameter concatenation, which can cause SQL injections and is a poor practice:
SqlCommand cmd2 = con.CreateCommand();
cmd2.CommandType = CommandType.Text;
cmd2.CommandText = "Select Pid From Provinces where Pname=@pr";
cmd2.Parameters.Add(new SqlParameter("pr", pr));
int result = Convert.ToInt32(cmd2.ExecuteScalar());
Alternativly, you can use fill a DataTable with multiple results:
SqlCommand cmd2 = con.CreateCommand();
cmd2.CommandType = CommandType.Text;
cmd2.CommandText = "Select Pid From Provinces where Pname=@pr";
cmd2.Parameters.Add(new SqlParameter("pr", pr));
SqlConnection Connection = new SqlConnection(ConnectionString);
SqlDataAdapter adp = new SqlDataAdapter(cmd2);
// Create a new datatable which will hold the query results:
DataTable dt = new DataTable();
Connection.Open();
// Fill a datatable with the query results:
adp.Fill(dt);
Connection.Close();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With