Reputation: 35
G_ID is an integer column in Groups table. I want the maximum value of it. When I trace below code I receive the error I've mentioned in code. Reader.HasRows equals true during debugging. So why it says "no data is present"
SqlConnection sqlc= new SqlConnection("data source=. ; database=LDatabase; integrated security=true");
SqlCommand cmd= new SqlCommand("select MAX(G_ID) as MAXID from Groups", sqlc);
sqlc.Open();
SqlDataReader Reader= cmd.ExecuteReader();
int MaxID = 0;
if (Reader.HasRows)
{
MaxID = Convert.ToInt32(Reader["MAXID"].ToString());// Here I receive this error: System.InvalidOperationException: Invalid attempt to read when no data is present.
MaxID += 1;
}
Upvotes: 0
Views: 1455
Reputation: 216273
Before accessing a DataReader you need to call the method Read to position the reader on the first record
SqlConnection sqlc= new SqlConnection("data source=. ; database=LDatabase; integrated security=true");
SqlCommand cmd= new SqlCommand("select MAX(G_ID) as MAXID from Groups", sqlc);
sqlc.Open();
SqlDataReader Reader= cmd.ExecuteReader();
int MaxID = 0;
if (Reader.Read())
{
MaxID = Convert.ToInt32(Reader["MAXID"].ToString());
MaxID += 1;
}
By the way, your query returns just one row and one column from the DB so a better approach is to use the ExecuteScalar method
SqlCommand cmd= new SqlCommand("select MAX(G_ID) as MAXID from Groups", sqlc);
sqlc.Open();
object result = cmd.ExecuteScalar();
if (result != null)
{
MaxID = Convert.ToInt32(result) + 1;
}
Upvotes: 3
Reputation: 10014
You are checking if the reader has rows but you are not reading them. Do this instead (note I'm also wrapping things to make sure they gets disposed properly):
SqlConnection sqlc= new SqlConnection("data source=. ; database=LDatabase; integrated security=true");
SqlCommand cmd = new SqlCommand("select MAX(G_ID) as MAXID from Groups", sqlc);
sqlc.Open();
try {
using (SqlDataReader reader = cmd.ExecuteReader()) {
int MaxID = 0;
while (reader.Read()) {
MaxID = Convert.ToInt32(Reader["MAXID"].ToString());
MaxID += 1;
}
}
}
finally {
sqlc.Close();
}
Upvotes: 0