Pregunta

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();
¿Fue útil?

Solución 2

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

Otros consejos

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));
}
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();
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top