Click here to Skip to main content
15,888,286 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hi Everyone,

I am trying to display the result of T-SQL aggregate function(e.g. sum) on a windows form using C# but I'm getting errors. could anybody help. below is the codes I've tried.

What I have tried:

C#
string selectcom1=select sum(Inv),StaffNumber, DATEPART(year,Date)  from Grawu  where datepart(YEAR,[Date])='2015'
group by StaffNumber, DATEPART(YEAR,[Date])

SqlCommand comm1 = new SqlCommand(selectcom1, connection);
 comm1.CommandType = CommandType.StoredProcedure;
 comm1.Parameters.AddWithValue("@year", cmbyear.SelectedItem);

SqlDataReader dr1 = comm1.ExecuteReader();
   if (dr1.Read())
       {
        year = dr1["year"].ToString();
                             
        Messagebox.Show("Anwer"+ dr1["inv"].ToString());

       }
Posted
Updated 22-Feb-16 11:48am
v2
Comments
Maciej Los 22-Feb-16 17:06pm    
You missed ["] double quotes around select statement:
string selectcom1=@"select sum(Inv),StaffNumber, DATEPART(year,Date) from Grawu where datepart(YEAR,[Date])='2015'
group by StaffNumber, DATEPART(YEAR,[Date])";

You forgot to define parameter for inside select statement.
sisey shaban 22-Feb-16 17:47pm    
Thanks Maceij, but that isn't the problem. the problem is the aggregate function(e.g. sum(inv)) displays better on management studio but not on windows form. I think I'm missing something. thanks again.
Maciej Los 22-Feb-16 17:49pm    
Please, see my answer.

1 solution

Please, read my comment to the question.

Check this:
C#
string selectcom1=@"select sum(Inv) As SumOfInv, StaffNumber, YEAR([Date]) AS Year
FROM Grawu 
WHERE YEAR([Date])=@year
GROUP BY StaffNumber, YEAR([Date])";


The rest of your code, you should change respectivelly to the MSDN documentation:
SqlCommand.CommandType Property (System.Data.SqlClient)[^]
Configuring Parameters and Parameter Data Types[^]
SqlCommand.ExecuteReader Method (System.Data.SqlClient)[^]
Retrieving Data Using a DataReader[^]
 
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