Click here to Skip to main content
16,004,887 members
Please Sign up or sign in to vote.
1.50/5 (2 votes)
See more:
I am deleting partiuclar row in gridview.

Run mode as follows


Waitlistid Course Batchdate
1 AFF 25 Aug 2014
2 MFA 26 Sep 2015
3 ERS 20 Mar 2012
4 ROC 19 Jul 2012


My code as follows

protected void OnRowDeleting(object sender, GridViewDeleteEventArgs e)
{

int index = Convert.ToInt32(e.RowIndex);
DataTable dt = ViewState["dt"] as DataTable;
dt.Rows[index].Delete();
ViewState["dt"] = dt;
BindGrid();
}


protected void BindGrid()
{
GridView1.DataSource = ViewState["dt"] as DataTable;
GridView1.DataBind();
}

When i delete the 4th row in gridview in row mode shows error as follows

Object reference not set to an instance of an object.

The above error shows in below line as follows

dt.Rows[index].Delete();

please help me. what is the problem in my abvoe code.
Posted
Comments
[no name] 29-May-15 0:28am    
I am deleting partiuclar row in gridview.

Run mode as follows


Waitlistid Course Batchdate
1 AFF 25 Aug 2014
2 MFA 26 Sep 2015
3 ERS 20 Mar 2012
4 ROC 19 Jul 2012


My code as follows

protected void OnRowDeleting(object sender, GridViewDeleteEventArgs e)
{

int index = Convert.ToInt32(e.RowIndex);
DataTable dt = ViewState["dt"] as DataTable;
dt.Rows[index].Delete();
ViewState["dt"] = dt;
BindGrid();
}


protected void BindGrid()
{
GridView1.DataSource = ViewState["dt"] as DataTable;
GridView1.DataBind();
}

When i delete the 4th row in gridview in row mode shows error as follows

Object reference not set to an instance of an object.

The above error shows in below line as follows

dt.Rows[index].Delete();

please help me. what is the problem in my abvoe code.

 
Share this answer
 
The reason for the exception "Object reference not set to an instance of an object." is your dt should be null.

Always check dt is not null and has rows before deleting. Change your code to something like below, so delete is success if the conditions are met and no exception is thrown where there is no data.

DataTable dt = ViewState["dt"] as DataTable;
if(dt != null && dt.Rows.Count > 0)
{
  dt.Rows[index].Delete();
}

I hope this gives an idea of what is wrong in your code and helps solve it.
 
Share this answer
 
try to dt.Rows.RemoveAt(index)
 
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