How do I change this:
using (SqlCommand myCommand = myConnection.CreateCommand())
{
myConnection.Open();
myCommand.CommandText = "SELECT FormID FROM tbl_Form";
using (SqlDataReader reader = myCommand.ExecuteReader())
{
while (reader.Read())
{
int FormID = reader.GetInt32(reader.GetOrdinal("FormID"));
MessageBox.Show(FormID.ToString());
}
}
}
to get MAX(FormID) ?
My natural tendency is to throw a MAX around FormID but I'm getting an IndexOutOfRange exception.
When you select the maximum id you shouldn't use a SqlDataReader
- the query returns just one item, which by default is unnamed so your existing query breaks because it expects a result named "FormID" - although you could have "fixed" your query by using "SELECT MAX(FormID) as FormId FROM tbl_Form"
. Instead use ExecuteScalar()
:
myCommand.CommandText = "SELECT MAX(FormID) FROM tbl_Form";
int maxId = Convert.ToInt32(myCommand.ExecuteScalar());
It's been a while since I used this style of database access, but I think you just need
select max(FormID) from tbl_Form
along with a call to ExecuteScalar
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.