Display SQL query result in a label in asp.net

33.7k views Asked by At

I'm trying to display the SQL query result in a label but it's not showing. This is my code:

     string result = "SELECT ACTIVE FROM [dbo].[test] WHERE ID = '" + ID.Text + "' ";
     SqlCommand showresult = new SqlCommand(result, conn);
     conn.Open();
     showresult.ExecuteNonQuery();
     string actresult = ((string)showresult.ExecuteScalar());
     ResultLabel.Text = actresult;
     conn.Close();

Need help please. Thanks!

5

There are 5 answers

0
CCBlackburn On

Is there a typo in there? You have two calls to the database:

showresult.ExecuteNonQuery();

This won't return a value and I'm not sure why you would have it there

string actresult = ((string)shresult.ExecuteScalar());

Unless you have a shresult variable, this query should error. What is the shresult variable?

1
hallie On

Try this one.

   string result = "SELECT ACTIVE FROM [dbo].[test] WHERE ID = '" + ID.Text + "' ";
   SqlCommand showresult = new SqlCommand(result, conn);
   conn.Open();
   ResultLabel.Text = showresult.ExecuteScalar().ToString();
   conn.Close();
2
KV Prajapati On

Use SqlParameter to filter the result and call ExecuteScalar() or ExecuteReader() method.

 string result = "SELECT ACTIVE FROM [dbo].[test] WHERE ID=@ID";
 SqlCommand showresult = new SqlCommand(result, conn);
 // If ID is int type
 showresult.Parameters.Add("@ID",SqlDbType.Int).Value=ID.Txt; 

 // If ID is Varchar then 
 //showresult.Parameters.Add("@ID",SqlDbType.VarChar,10).Value=ID.Txt; 

  conn.Open();
  string actresult = (string)showresult.ExecuteScalar(); 
  conn.Close();
  if(!string.IsNullOrEmpty(actresult))
       ResultLabel.Text = actresult;
  else
       ResultLabel.Text="Not found";
0
JP Hellemons On
using (SqlConnection conn = new SqlConnection(connectionString))
{
    string result = "SELECT ACTIVE FROM [dbo].[test] WHERE ID = @id";
    SqlCommand showresult = new SqlCommand(result, conn);
    showresult.Parameters.AddWithValue("id", ID.Text);

    conn.Open();
    ResultLabel.Text = showresult.ExecuteScalar().ToString();
    conn.Close();
}

This will dispose the connection and has no string concatenation in the query.

1
Govind Tiwari On
 conn.Open(); 
 string result = "SELECT ACTIVE FROM test WHERE ID = '" + ID.Text + "' ";
 SqlCommand showresult = new SqlCommand(result, conn);

 showresult.ExecuteNonQuery();
 int actresult = ((int)showresult.ExecuteScalar());
 ResultLabel.Text = actresult.Tostring();
 conn.Close();