Click here to Skip to main content
15,886,110 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi, would someone please tell me whats wrong.

I have a SQL Table that stores the runtime mins of a machine against the date it was running.
If the machine is powered down for longer than 10 mins, the code writes a second runtime entry with the same date, effectively leaving 2(or more) entries with the same date.

SQL
eg
Date       |Runtime

15/11/2013 |120
16/11/2013 |140
16/11/2013 | 70

if i run the sql query
SQL
select sum(ActualRunTime) from MonthlyRunData where Date = '16/11/2013'

returns 210
Now, i am trying to do this in c# so here is my code
C#
conX.Open();
SqlCommand readRunTimeActual = new SqlCommand();
readRunTimeActual.Connection = conX;
string sqlreadRunTimeActual = "Select sum(ActualRunTime) from MonthlyRunData " +
                              "where Date = '16/11/2013'";

readRunTimeActual.CommandText = sqlreadRunTimeActual;
SqlDataReader getRunTimeActual;
getRunTimeActual = readRunTimeActual.ExecuteReader();
getRunTimeActual.Read();

string runActual = (getRunTimeActual[("ActualRunTime")].ToString());
actRunTimeTot = int.Parse(runActual);
conX.Close();

This returns 'IndexOutofRange Exception' at the point highlighted in bold above.
I do not know why. It works in SQL fine.
Thank you in advance.
Posted
Updated 21-Nov-13 19:00pm
v3
Comments
Er Daljeet Singh 22-Nov-13 1:11am    
string runActual = (getRunTimeActual[0].ToString());
it will work only in case when your query will return atleast single record.
Davey85 22-Nov-13 1:15am    
Thank you very much for your response.

1 solution

I think the field "ActualRunTime" name is not defined.
Try one of this.
1.
C#
string sqlreadRunTimeActual = "Select sum(ActualRunTime) ActualRunTime from MonthlyRunData " + "where Date = '16/11/2013'";

2. (getRunTimeActual[0].ToString()); I am not sure if first field index is 0 or 1. I am guessing its 0.
 
Share this answer
 
v3
Comments
Davey85 22-Nov-13 1:12am    
Thank you very much!
ArunRajendra 22-Nov-13 1:23am    
your welcome :)
Davey85 25-Nov-13 1:06am    
sorry to bother you again but how would you do the same thing but with a summed multiplication?

"Select sum(Lenth * Quantity) from CoilRunData " + "where Date = '16/11/2013'";
ArunRajendra 25-Nov-13 1:58am    
Just give an alias as shown Select sum(Lenth * Quantity) Total from CoilRunData " + "where Date = '16/11/2013'
Davey85 25-Nov-13 17:07pm    
Yes, i understand it now, you are assigning the result of the multiplication to 'Total' and summing the result. When you assigned 'ActualRunTime' in the initial question under the same name it worked but i didnt get why, now i do. Thank you very much for your help.

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