How do I retrieve the result of an ADO.NET SqlCommand?

Ok either I’m really tired or really thick at the moment, but I can’t seem to find the answer for this

I’m using ASP.NET and I want to find the amount of rows in my table.

I know this is the SQL code: select count(*) from topics, but how the HECK do I get that to display as a number?

All I want to do is run that code and if it = 0 display one thing but if it’s more than 0 display something else. Help please?

This is what I have so far

string selectTopics = "select count(*) from topics";
// Define the ADO.NET Objects
SqlConnection con = new SqlConnection(connectionString);
SqlCommand topiccmd = new SqlCommand(selectTopics, con);
if (topiccmd == 0)
    {
        noTopics.Visible = true;
        topics.Visible = false;
    }

but I know I’m missing something seriously wrong. I’ve been searching for ages but can’t find anything.

PHP is so much easier. 🙂

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

Note that you must open the connection and execute the command before you can access the result of the SQL query. ExecuteScalar returns a single result value (different methods must be used if your query will return an multiple columns and / or multiple rows).

Notice the use of the using construct, which will safely close and dispose of the connection.

string selectTopics = "select count(*) from topics";
// Define the ADO.NET Objects
using (SqlConnection con = new SqlConnection(connectionString))
{
   SqlCommand topiccmd = new SqlCommand(selectTopics, con);
   con.Open();
   int numrows = (int)topiccmd.ExecuteScalar();
   if (numrows == 0)
    {
        noTopics.Visible = true;
        topics.Visible = false;
    }
}

Method 2

ExecuteScalar is what you’re looking for. (method of SqlCommand)

Btw, stick with C#, there’s no way PHP is easier. It’s just familiar.

Method 3

You need to open the connection
This might work :

SqlConnection sqlConnection1 = new SqlConnection("Your Connection String");
SqlCommand cmd = new SqlCommand();
SqlDataReader reader;

cmd.CommandText = "select count(*) from topics";
cmd.CommandType = CommandType.Text;
cmd.Connection = sqlConnection;
sqlConnection1.Open();

reader = cmd.ExecuteReader();
// Data is accessible through the DataReader object here.

sqlConnection1.Close();

Similar Question: C# ‘select count’ sql command incorrectly returns zero rows from sql server


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x