Hi
I have below code and i want to get the value of userid from table
SqlCommand cmd = new SqlCommand("Users", con);
cmd.CommandType = CommandType.Text;
con.Open();
cmd.ExecuteNonQuery();
int Status = Convert.ToInt32(cmd.ExecuteScalar());
Thanks
Adarsh NigamPosted Aug 20, 2024, 4:17 AM
It looks like you're trying to retrieve the value of
useridfrom theUserstable. However, there are a few issues with your code:cmd.CommandTypetoCommandType.Text, but you're not providing a SQL query. Instead, you're just specifying the table nameUsers.ExecuteNonQuery()which is used to execute a query that doesn't return any data. But you want to retrieve the value ofuserid, so you should useExecuteScalar()orExecuteReader()instead.ExecuteScalar()to an integer, but you haven't specified which column you want to retrieve.Here's an updated version of your code that should work:
SqlCommand cmd = new SqlCommand("SELECT userid FROM Users", con);
cmd.CommandType = CommandType.Text;
con.Open();
object result = cmd.ExecuteScalar();
int userid = Convert.ToInt32(result);
In this code, we're specifying a SQL query that selects the
useridcolumn from theUserstable. We're then callingExecuteScalar()to retrieve the first column of the first row of the result set. Finally, we're converting the result to an integer usingConvert.ToInt32().Note that if your table has multiple rows, this code will only retrieve the
useridvalue from the first row. If you want to retrieve all theuseridvalues, you'll need to useExecuteReader()instead.