Syed Salman Raza Zaidi
Syed Salman Raza Zaidi

Reputation: 2192

GridView is hiding after Row Deleting Event

I am using GridView Row command Event for deleting row from Gridview, I have added RowDeleting Event of gridview, but after deleting the GridView is getting hide. Below is my code

 protected void Page_Load(object sender, EventArgs e)
        {
       if (!Page.IsPostBack){
LoadData()//Here I am databinding the Grid
}
}

private void LoadData()
{
var data=MyClass.GetRecords();//it returns  DataTable
dg.DataSource=data;
dg.DataBind();
}
protected void dg_RowCommand(Object sender, GridViewCommandEventArgs e)
{
    if(e.CommandName =="del")
    {
        //Delete Records
        dg.DataBind();
    }

}

public void dg_RowDeleting(Object sender, GridViewDeleteEventArgs e)
{
    dg.DataBind();
} 

Upvotes: 2

Views: 865

Answers (2)

Markus
Markus

Reputation: 22481

The GridView does not show any records because you do not assign a DataSource to it before calling DataBind in dg_RowDeleting.

You need to reassign the DataSource before calling DataBind anew, because it is not set again on a PostBack.

So a typical approach for the Delete part of your dg_RowCommand method would be:

  1. Identify the row that is to be deleted. Remove the row from the database.
  2. Reload the data from the database.
  3. Assign the data to the DataSource property.
  4. Bind the GridView by calling DataBind().

For steps 2-4 you will be able to call your LoadData method from dg_RowCommand. You only need to implement dg_RowDeleting if you do not implement the deletion yourself but want to do something when a row is deleted.

Upvotes: 1

Vignesh Kumar A
Vignesh Kumar A

Reputation: 28413

My guess is you are missing DataSource after deleting the rows.

Try this

protected void dg_RowCommand(Object sender, GridViewCommandEventArgs e)
{
    if(e.CommandName =="del")
    {
        //Delete Records
       LoadData();
    }

}

public void dg_RowDeleting(Object sender, GridViewDeleteEventArgs e)
{
    LoadData();
} 

Upvotes: 1

Related Questions