Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
596 views
Welcome To Ask or Share your Answers For Others

1 Answer

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());

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...