Rane Mokles
Rane Mokles

Reputation: 23

Query Sql to return value

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

Upvotes: 2

Views: 110

Answers (3)

Tobberoth
Tobberoth

Reputation: 9537

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

Upvotes: 0

Mike Perrenoud
Mike Perrenoud

Reputation: 67948

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

Upvotes: 1

Dmytro Rudenko
Dmytro Rudenko

Reputation: 2524

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

Upvotes: 0

Related Questions