Click here to Skip to main content
16,022,737 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
C#
public int membercount(string tbl, string condition)
    {
        string query = null;
        if (condition.Trim().Length > 0) 
        {
            query = query + "where" + condition;
        }
        else
        {
            query = query;
        }
        cmd = new SqlCommand(query, con);
       dr= cmd.ExecuteScalar();
        return a;   
    }
Posted
Updated 7-Jun-13 0:00am
v3
Comments
lukeer 7-Jun-13 8:14am    
Don't post the same question[^] again.
Use the "Improve question" link beneath your original question instead to provide further insight that can help potential answerers helping you.

As I can see in your code block, dr is SqlDataReader object. Where as cmd.ExecuteScalar()[^] returns the first column of the first row in the result set returned by the query. Additional columns or rows are ignored.

Additionally, I can see one more problem in your code is, your SQL query is wrong. I am modifying the query here. You can check it once.
Try this:
C#
public int membercount(string tbl, string condition)
{
    string query = "SELECT COUNT(*) FROM " + tbl; //Since your function is for counting member.
    if (condition.Trim().Length > 0)
    {
        query = query + " where " + condition;
    }
    cmd = new SqlCommand(query, con);
    int a = Convert.ToInt32(cmd.ExecuteScalar());//Converting the returned value to Int32
    return a;
}



--Amit
 
Share this answer
 
Actually the Executescaler() method returns

the first column of the first row in the result set returned by the query. Additional columns or rows are ignored.

but u have assigned it to the dr .Thats why u are getting this error.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900