Click here to Skip to main content
15,905,028 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I'm having problem populating a Label with average value from MSSQL database.
The code written in database is this:
SQL
ALTER PROCEDURE [dbo].procTakeAverage

(
@ID_Person int


)
AS
	BEGIN
	SELECT AVG (RATING.Grade) from RATING
	inner join SUBJECT on SUBJECT.ID_Subject= RATING.ID_Subject
	where RATING.ID_Subject = @ID_Person and RATING.ID_RatingType=1
	END

This stored procedure works perfectly and returns the average value.
The problem is how to show this value in a Label using ASP.NET technology (code).

This is what I tried so far.

What I have tried:

<pre><pre lang="c#">
public void AverageValue()
{
string average= String.Empty;
DataTable dt = new DataTable();
SqlConnection sqlConn = new SqlConnection("Here is the string connection");


try
{
sqlConn.Open();

SqlCommand sqlCmd = new SqlCommand("procTakeAverage", sqlConn);


sqlCmd.CommandType = CommandType.StoredProcedure;


sqlCmd.Parameters.Add("@ID_Person", SqlDbType.Int).Value = average;


sqlCmd.Parameters["@ID_Person"].Value = Convert.ToInt32(lblID_Nxenesi.Text);

sqlCmd.ExecuteNonQuery();
average = lblAverage.Text.ToString();

sqlConn.Close();

}
catch { }

}

This code is not showing me the average value in lblAverage.

Thank you in advance for your time.
Cheers.
Posted
Updated 6-Oct-18 7:21am

Why would it when you're not setting the label text anywhere?

sqlCmd.ExecuteNonQuery();


The above line executes the SELECT but ignores the results

average = lblAverage.Text.ToString();


This sets the local variable average to be the text that is in lblAverage, but you haven't set that text anywhere. You also pass "average" as the @ID_Person param but it's an empty string so that's not going to do anything either.

If your SP returns a single value and single row then use ExecuteScalar rather than ExecuteNonQuery to run the SP and return that value. You then set lblAverage.Text to be the value returned from the SP, and you also need to pass in the proper person ID.

Google for how to use ExecuteScalar if you don't know how.
 
Share this answer
 
I found a solution according to the
F-ES Sitecore
suggestions.
First I have had to use CASTING the values in MSSQL to the FLOAT Values.
Afterwards used the ExecuteScalar() method in the ASP.NET.
Once again thank you all for your reply.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900