Hi All,
I have a problem when I am using the max(ID) function with the data reader. I actually want to get the maximum ID from a table.
I am using a Data Reader, when I run the code, datareader HasRows function shows true but when I try to access the datareader [0], it shows an error like “Invalid attempt to read when no data is present.”.
Please help me in getting the max value in some variable which I will use where ever I need it.
Below is the code which I am using:
string Query = "Select max(IDfield) from Employee";
string connStr = "Data Source=.\\SQLEXPRESS;AttachDbFilename=|DataDirectory|\\S-L-Db.mdf;Integrated Security=True;User Instance=True";
SqlConnection mySqlConnection = new SqlConnection(connStr);
SqlCommand mySqlCommand = mySqlConnection.CreateCommand();
mySqlCommand.CommandText = Query;
mySqlConnection.Open();
SqlDataReader dr = mySqlCommand.ExecuteReader();
if (dr.HasRows == true)
{
string myMaxID = Convert.ToString(dr[0]);
return 2;
}
else
return 1;
mySqlConnection.Close();
catch (Exception ex)
throw ex;