Sena Sena - 4 years ago 101
C# Question

C# - SQL - Function of counting a table row will only count once?

I have getRowAmount() and add() function. I try to get the amount of row of a table with getRowAmount(). I add a value and calculate the ID or primary key based on getRowAmount + 1. So, when I add a value to the table and get the amount of row at the first time, it will work and ListView show rows and the amount is correct. But, when I try to add a value again (which means call the getRowAmount() again), It says there was a duplicate primary key. Here is my code:

public int getRowAmount(){

SqlCommand cmd = new SqlCommand("select count(*) from timelineTable", conn);
SqlAdapter adapter = new SqlAdapter(cmd);
DataTable virtualTable = new DataTable();
adapter.Fill(virtualTable);
int rowAmount = Convert.ToInt32(virtualTable.Rows[0][0].ToString());
return rowAmount;
}


The function Above only count the row once when it is called. And I'm sorry i'm a beginner in C#. Any solution?
Thanks!

Answer Source

Instead of using SqlAdapter and DataTable, try using ExecuteScalar method from SqlCommand. It would be much simpler and should return the actual result from DataBase.

public int getRowAmount()
{
    SqlCommand cmd = new SqlCommand("select count(*) from timelineTable", conn);
    return cmd.ExecuteScalar();
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download