problem in displaying null value to the control in the footer template of gridview

Feb 13 2009 5:41 AM
Hi folks!
I am developing a web application in which I have a gridview in which there is footer template where i've put 3 labels that displays the sum of the values in their corresponding columns after retrieving data from the database. The sum of values are displayed correctly when there's some records retrieved from the database, but it doesnt work when there are no records retrieved from the db i get an erros tha says

Object reference not set to an instance of an object.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.

Here is my code:

Sub GetTotals()
Dim conn As SqlConnection = New SqlConnection(strConn)
Dim cmd As SqlCommand = New SqlCommand
cmd.CommandText = "select ISNULL(SUM(amount_taken),0.00) as 'Amount_Taken', ISNULL(SUM(loan_Installment),0.00) as 'loan_Installment',ISNULL(SUM(loan_balance),0.00) as 'loan_balance' from Loans where employee_no=@Employee_no"
cmd.Connection = conn
cmd.CommandType = CommandType.Text
cmd.Parameters.AddWithValue("@Employee_no", Session("Employee_no"))
conn.Open()
cmd.ExecuteNonQuery()
Dim MyReader As SqlDataReader
MyReader = cmd.ExecuteReader
MyReader.Read()

'The error occurs here when trying to get the controls in the footer template
Dim Total_AmountTaken As Label = CType(GridViewloans.FooterRow.FindControl("lblTotAmountTaken"), Label)
Dim Total_LoanInstallment As Label = CType(GridViewloans.FooterRow.FindControl("lblTotMonthlyInstallment"), Label)
Dim Total_LoanBalance As Label = CType(GridViewloans.FooterRow.FindControl("lblTotLoanBalance"), Label)

Total_LoanInstallment.Text = String.Format("{0:#,###.00}", MyReader("Loan_Installment")).ToString
Total_LoanBalance.Text = String.Format("{0:#,###.00}", MyReader("Loan_Balance")).ToString
Total_AmountTaken.Text = String.Format("{0:#,###.00}", MyReader("amount_taken")).ToString
conn.Close()
cmd.Dispose()
MyReader.Close()
EndSub

As you can from the sql statement i tried to use the ISNULL() just the default values when the it is null but still it does not work.

I hope i've describe my problem clearly
Please somebody help me.

Answers (2)