C# – to find max value from a given table in sql express

c++, sql, sql-server

i am trying to retrieve latest data from my database table.
i am using max(columnName) but not having result to my liking.
i keep getting column name instead of any value

please help me out in this…

the code for retrieving max value is like this

            dbConnection dbCon = new dbConnection();            con = dbCon.doConnection();            SqlCommand cmd = new SqlCommand();            String query = "select max(studentNo) from studentInfo;";            cmd.Connection = con;            cmd.CommandText = query;            SqlDataReader reader = cmd.ExecuteReader();            while (reader.Read())            {                 String x=reader["studentNo"].ToString();            }

here the studentNo is the column name whose value i need to extract and it is of int type
while printing the string x on my application i get studentNo instead of the value.
now i am short of clue to solve the prob because i can't find anything wrong with the code.
do help me in this one

Best Solution

The problem is in the way you are accessing the value, you can change two things here. Either access the reader by index or name the column appropriately in the query.

select max(studentNo) as StudentNo from studentInfo;