Home > Software engineering >  How to delete row from gridview with List<> Datasource using OnRowDeleting
How to delete row from gridview with List<> Datasource using OnRowDeleting

Time:01-05

Gridview.Datasource=List<T>

Gridview.Databind();


protected void Grid_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
}

CodePudding user response:

You did not provide much information, but you can use OnRowDeleting as follows:

From doc

The RowDeleting event is raised when a row's Delete button is clicked, but before the GridView control deletes the row. This enables you to provide an event-handling method that performs a custom routine, such as canceling the delete operation, whenever this event occurs.

What you have is that RowIndex so first you need to find a related item from your List (Datasource) and remove it and then bind it to gridview again something like this:

protected void OnRowDeleting(object sender, GridViewDeleteEventArgs e)
{
    int index = Convert.ToInt32(e.RowIndex);

    //Assuming resultList is the datasource,
    var itemToRemove = resultlist.SingleOrDefault(r => r.Id == index); 
    if (itemToRemove != null)
        resultList.Remove(itemToRemove);
    
    Gridview.Datasource = resultList;
    Gridview.Databind();
}

Hope it navigates you right direction!

CodePudding user response:

I hope that this helps you to done it well :

https://www.aspsnippets.com/questions/166407/Delete-row-from-GridView-and-ViewState-using-C-and-VBNet-in-ASPNet/

  •  Tags:  
  • Related