0

I'm coding a simple application using c# asp.net. I'm getting the averages of columns. How can I get the individual values from the result and display it in a new label (label1, label2, label3....)?

I tried ExecuteScalar().ToString(); but it returns only the first column.

Below is my code:

SqlConnection con;
con = new SqlConnection("Data Source=.\\SQLEXPRESS;AttachDbFilename=|DataDirectory|\\STATDB.MDF;Integrated Security=True;User Instance=True");
SqlCommand com = new SqlCommand();

SqlDataAdapter da = new SqlDataAdapter();
string result = "SELECT AVG(p_tan) AS p_tang, AVG(e_tan) AS e_tang, AVG(p_rel) AS p_reli FROM statistics";
SqlCommand showresult = new SqlCommand(result, con);
con.Open();

Label1.Text = showresult.ExecuteScalar().ToString();
//Label2.Text = p_tang
//Label3.Text = e_tang
//Label4.Text = p_reli
con.Close();

Any help will be appreciated.

1

2 Answers 2

3

Use showresult.ExecuteReader() and then iterate over the row to get the values

SqlDataReader reader=showresult.ExecuteReader();
while (reader.Read())
{
  Label1.Text= reader["p_tang"].ToString().Trim();
  Label2.Text= reader["e_tang"].ToString().Trim();
  Label3.Text= reader["p_reli"].ToString().Trim();
}
Sign up to request clarification or add additional context in comments.

Comments

0

ExecuteScalar will only pull one value. You will need do either use a DataReader or DataAdapter to get multiple values from the database.

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.