2

I want to write Query to display value in MessageBox , but it is not true :

SqlDataReader myReader = null;
SqlCommand myCommand = new SqlCommand("select BillNumber from BillData", cn);
cn.Open();
myReader = myCommand.ExecuteReader();
MessageBox.Show(myReader.ToString());
cn.Close();
2
  • C# or Java? You should choose just one. Commented Nov 19, 2013 at 14:14
  • Looks like C#. I have attempted to edit the question to remove Java from the tags. Commented Nov 19, 2013 at 14:15

3 Answers 3

1

You would need to do this:

myReader.GetString(0);

However, there is a bit more that needs done here. You need to leverage the ADO.NET objects properly:

var sql = "select BillNumber from BillData";
using (SqlConnection cn = new SqlConnection(cString))
using (SqlCommand cmd = new SqlCommand(sql, cn))
using (SqlDataReader rdr = cmd.ExecuteReader())
{
    rdr.Read();
    MessageBox.Show(rdr.GetString(0));
}
Sign up to request clarification or add additional context in comments.

1 Comment

You need a rdr.Read() to load the first row after you execute rdr.
0

When you just want one return value, you can use ExecuteScalar() like this:

SqlCommand myCommand = new SqlCommand("select BillNumber from BillData", cn);
cn.Open();
string return_value = myCommand.ExecuteScalar().ToString();
MessageBox.Show(return_value);
cn.Close();

Comments

0
SqlDataReader myReader = null;
SqlCommand myCommand = new SqlCommand("select BillNumber from BillData", cn);
cn.Open();
myReader = myCommand.ExecuteReader();
myReader.Read();
MessageBox.Show(myReader["BillNumber"].ToString());
cn.Close();

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.