Reputation: 17
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.
Upvotes: 0
Views: 875
Reputation: 3834
ExecuteScalar
will only pull one value. You will need do either use a DataReader
or DataAdapter
to get multiple values from the database.
Upvotes: 0
Reputation: 40970
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();
}
Upvotes: 3