Error:Object reference not set to an instance of an object

Posted by Sheesh under Regular Expressions on 3/11/2011 | Points: 10 | Views : 10439 | Status : [Member] | Replies : 10
Hi
Small problem occur, while executing a update procedure in asp.net it shows object reference not set to an instance of an object, can't understand. This is a small prog that have 3 tier architecture. The Stored procedure is perfectly executing have no problem.
The connection string it is perfectly right, because records are fetched from table to grid. On fixing the break point it throws the error in the Updaterec method. Morever in this statement TextBox Tname = (TextBox)row.FindControl("Txtname");
the object tname shows null values & procedings objects also.
The compiler throws the error from catch statement.
Following is the code
protected void EditRec(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
BindGrid();
}
protected void BindGrid()
{
GridView1.DataSource = GridDatsource();
GridView1.DataBind();
}
private DataTable GridDatsource()
{
DataTable dtable = new DataTable();
try
{
dtable = B1.Loads();
}
catch (Exception ee)
{
throw (ee);
}
return dtable;
}
protected void UpdateRec(object sender, GridViewUpdateEventArgs gUe)
{
int res=0;
GridViewRow row = (GridViewRow)GridView1.Rows[gUe.RowIndex];
TextBox Tname = (TextBox)row.FindControl("Txtname");
TextBox Tsal = (TextBox)row.FindControl("TxtSal");
TextBox TDsg = (TextBox)row.FindControl("TxtDsg");
try
{
res = B1.Modi(Tname.Text, float.Parse(Tsal.Text), TDsg.Text);
if (res > 0)
Label6.Text = "Record Updated Successfully";
else
Label6.Text = "Record Not Updated";
}
catch (Exception EE)
{
Label7.Text = EE.Message.ToString();
}
finally
{
B1 = null;
}
}
protected void CancelRec(object sender, GridViewCancelEditEventHandler gCe)
{
GridView1.EditIndex = -1;
BindGrid();
}
Buisness Layer
public int Modi(String Emname, float Salary, String Desig)
{
try
{
return eDal.UpdateRec(Emname, Salary, Desig);
}
catch
{
throw;
}
finally
{
eDal = null;
}
}
public DataTable Loads()
{
try
{
return eDal.Load();
}
catch
{
throw;
}
finally
{
eDal = null;
}
}
Data Layer
public DataTable Load()
{
SqlConnection conn = new SqlConnection(Cns);
conn.Open();
SqlDataAdapter dAd = new SqlDataAdapter("UspDisplayRec", conn);
dAd.SelectCommand.CommandType = CommandType.StoredProcedure;
DataSet dSet = new DataSet();
try
{
dAd.Fill(dSet, "Employee");
return dSet.Tables["Employee"];
}
catch(Exception E)
{
throw E;
}
finally
{
dSet.Dispose();
dAd.Dispose();
conn.Close();
conn.Dispose();
}
}
public int UpdateRec(String Ename, float sal, String Desig)
{
SqlConnection conn = new SqlConnection(Cns);
conn.Open();
SqlCommand dCmd = new SqlCommand("UspModiRec", conn);
dCmd.CommandType = CommandType.StoredProcedure;
try
{
dCmd.Parameters.AddWithValue("Ename", Ename);
dCmd.Parameters.AddWithValue("Sal", sal);
dCmd.Parameters.AddWithValue("Desig", Desig);
return dCmd.ExecuteNonQuery();
}
catch (Exception E)
{
throw E;
}
finally
{
dCmd.Dispose();
conn.Close();
conn.Dispose();
}
}
Thanks
Regards

Thanks
Regards



Responses

Posted by: Chvrsri on: 3/11/2011 [Member] [Moderator] [MVP] Silver | Points: 25

Up
0
Down

Hi,

This Error generally comes when you are not handling null values. Please check whether your database query returning any null values or if you implicitly assign any null values.

Thanks,
Radha Srikanth

Sheesh, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Sheesh on: 3/11/2011 [Member] Starter | Points: 25

Up
0
Down
Hi,
Well the query is not returning any null values.. Infact the whole grid is filled with records after fetching from table. Morever somebody has suggest me to use e.NewValues["<DatafieldName>"] instead of Findcontrol in RowUpdating event. Even i have applied for that also like this
string Tname = gUe.NewValues["Ename"].ToString();
string Tsal = gUe.NewValues["Sal"].ToString();
string TDsg = gUe.NewValues["Dsg"].ToString();
then too the same error occurs

Here is the Grid Code
<asp:GridView ID="GridView1" runat="server" AllowPaging="True"
AllowSorting="True" AutoGenerateColumns="False"
AutoGenerateEditButton="True" CellPadding="4"
OnRowEditing="EditRec" OnRowUpdating="UpdateRec"
PageSize="5"
style="margin-left: 28px"
OnPageIndexChanging="ChangePage" OnSorting="SortRecords"
ForeColor="#333333" GridLines="None">
<RowStyle BackColor="#FFFBD6" ForeColor="#333333" />
<Columns>
<asp:BoundField DataField="Ename" HeaderText="Employee Name" />
<asp:BoundField DataField="Sal" HeaderText="Salary" />
<asp:BoundField DataField="Desig" HeaderText="Designation" />
</Columns>
<FooterStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#FFCC66" ForeColor="#333333" HorizontalAlign="Center" />
<SelectedRowStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="Navy" />
<HeaderStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />
<AlternatingRowStyle BackColor="White" BorderStyle="Groove" />
</asp:GridView>

After debugging several times I tested on below code

string xx = row.Cells[2].Text;
Here I found that it returns null values. What i am thinking if it is returning null values , then how could it find the control. but can't understand the
this code string Tname = gUe.NewValues["Ename"].ToString(); which returns "Object reference not set to an instance of an object"

could you please tell whether i am debugging in right direction or not. any other suggestion for executing this task..


Thanks
Regards

Sheesh, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Chvrsri on: 3/11/2011 [Member] [Moderator] [MVP] Silver | Points: 25

Up
0
Down
Kindly find the value in the DB with the column assigning with cells[2] . Also observe whether you are applying the value into the grid using the same Data type. Are you casting it properly?

Thanks,
Radha Srikanth

Sheesh, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Sheesh on: 3/11/2011 [Member] Starter | Points: 25

Up
0
Down
In the Db the column is Nvarchar type & contains some dummy record as text or you can say string. Regarding the casting it is executing properly, no errors occurs while executing & the datatype is similar to that of present in DB & in the business class.

Thanks
Regards

Sheesh, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Gsolvers on: 3/11/2011 [Member] Starter | Points: 25

Up
0
Down
Can you zip and send across the project?

Best Regards,

VG
www.TeacherJi.com

Sheesh, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Madhu.b.rokkam on: 3/11/2011 [Member] [MVP] Bronze | Points: 25

Up
0
Down
If what ever code you have posted is the final one then I could see that you have always nullified the class objects calling the methods but there is no sign where you have initialized them... Make sure in every method as you are makeing the objects to null, initialize them before calling any of the methods. That should rectify your issue...

Thanks and Regards
Madhu

Sheesh, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Sheesh on: 3/11/2011 [Member] Starter | Points: 25

Up
0
Down
Hi
Here is the attached zip just download from the link, as while attaching the zip ,everytime it creates an error, kindly change the Data Source name of connection string present in the web.config file

http://www.fileflyer.com/view/UpOqHCS

Thanks
Regards

Thanks
Regards

Sheesh, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Sheesh on: 3/12/2011 [Member] Starter | Points: 25

Up
0
Down
Hi,
If you are thinking about the class object B1, then it's ok because i have set it to nullify in the finally statement, but this object is intialized in the public partial class in the Empmain, so to get rid off initilizaton everytime on calling method. But the real problem after debugging several times in the update method. The object row present as
GridViewRow row = (GridViewRow)GridView1.Rows[gUe.RowIndex];
always have null values & that's why it throws an exception handler error message "Object reference not set to an instance of an object"
& that's main thing I can't get the solution as how it gets the null values.


Thanks
Regards

Sheesh, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Gsolvers on: 3/13/2011 [Member] Starter | Points: 25

Up
0
Down
Can you try this?
GridViewRow row = (GridViewRow)GridView1.Rows[gUe.RowIndex-1];


Best Regards,

VG
www.TeacherJi.com

Sheesh, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Sheesh on: 3/13/2011 [Member] Starter | Points: 25

Up
0
Down
Hi,
I have tried this code also, but it throws an error
"Index was out of range. Must be non-negative and less than the size of the collection."

Even When i tried this code
int autoid = Int32.Parse(GridView1.DataKeys[e.RowIndex].Value.ToString());
in the updateRec method then it raises the error message

Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index
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.ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index

Source Error:


Line 61:
Line 62:
Line 63: int autoid = Int32.Parse(GridView1.DataKeys[e.RowIndex].Value.ToString());
Line 64: //string xx = row.Cells[1].Text;
Line 65: //string Txt = gUe.OldValues[2].ToString();


Source File: c:\EMS\EmpMain.aspx.cs Line: 63

Stack Trace:


[ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index]
System.Collections.ArrayList.get_Item(Int32 index) +7483656
System.Web.UI.WebControls.DataKeyArray.get_Item(Int32 index) +12
EmpMain.UpdateRec(Object sender, GridViewUpdateEventArgs e) in c:\EMS\EmpMain.aspx.cs:63
System.Web.UI.WebControls.GridView.OnRowUpdating(GridViewUpdateEventArgs e) +133
System.Web.UI.WebControls.GridView.HandleUpdate(GridViewRow row, Int32 rowIndex, Boolean causesValidation) +720
System.Web.UI.WebControls.GridView.HandleEvent(EventArgs e, Boolean causesValidation, String validationGroup) +704
System.Web.UI.WebControls.GridView.OnBubbleEvent(Object source, EventArgs e) +95
System.Web.UI.Control.RaiseBubbleEvent(Object source, EventArgs args) +37
System.Web.UI.WebControls.GridViewRow.OnBubbleEvent(Object source, EventArgs e) +123
System.Web.UI.Control.RaiseBubbleEvent(Object source, EventArgs args) +37
System.Web.UI.WebControls.LinkButton.OnCommand(CommandEventArgs e) +118
System.Web.UI.WebControls.LinkButton.RaisePostBackEvent(String eventArgument) +135
System.Web.UI.WebControls.LinkButton.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) +10
System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +13
System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) +175
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +1565

This is stack trace error list. Now anyone could give the solution as where my logic is wrong



Thanks
Regards

Sheesh, if this helps please login to Mark As Answer. | Alert Moderator

Login to post response