0

How can I display single value from SQL Server database in C# ?

I have a total of 8 columns in database and I want to display a count of the 4th column in a MessageBox

cn.Open();
str = "select count(name) from Student";
cmd = new SqlCommand(str,cn);
reader = cmd.ExecuteReader();

MessageBox.Show(reader.ToString());

cmd.Dispose();
reader.Close();
cn.Close();

1 Answer 1

2

If you're looking for a single column of a single row, you can use ExecuteScalar

cn.Open();
str = "select count(name) from Student";
cmd = new SqlCommand(str,cn);
value = cmd.ExecuteScalar();

MessageBox.Show(value .ToString());

cmd.Dispose();
cn.Close();

If you expect multiple rows, you will need to iterate through each of the rows, using while (reader.Read()).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.