Click here to Skip to main content
15,035,600 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I need to count the number of records in a table.I tried like this -
SqlDataAdapter da = new SqlDataAdapter();
string select = "select count(*) as number from tblRegNo;
da.SelectCommand = new SqlCommand(select, con);

Then I need to assign this number to a integer variable.Then I can use a messagebox to view the number of records in the database table.
Please help me. I am a beginner for C# programming.
Posted

After Query Of Count Use:

SqlCommand cmd = new SqlCommand(select, con);
int Newvalue = Convert.ToInt32(cmd.ExecuteScalar());
   
Hi,

Try the below code

C#
string query = "select count(*) as number from tblRegNo";
SqlCommand cmd= new SqlCommand(query,con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
int noOfRecords=0;
If(ds.Table[0].Rows.Count>0)
{
   noOfRecords = Convert.ToInt32(ds.Table[0].Rows[0]["number"].ToString());
}
   
SQL
string select = "select* from tblRegNo";
SqlDataAdapter da = new SqlDataAdapter(select, con);
DataTable dt = new DataTable();
da.fill(dt);

var count= dt.Rows.Count.ToString();
MessageBox.Show(count);
   
Comments
NISHAN SANDEEPA 28-Nov-12 1:40am
   
Thank you so much Krunal.It was so helpful.Because I am a beginner for programming.
[no name] 28-Nov-12 1:43am
   
Welcome :)

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