Refresh DataPager after an item in ListView is deleted

908 Views Asked by At

I have a ListView table in my asp.net page. Against each row there is delete button. on clicking the button the corresponding item will be deleted.

I have done all these. Also to refresh the data after an item is deleted.

Here is my code:

aspx

<asp:ListView ID="CategoriesList" runat="server" ItemPlaceholderID="PlaceHolder1" OnPagePropertiesChanging="OnPagePropertiesChanging">
  <LayoutTemplate>
    <table>
      <tr><th>Header</th></tr>
      <asp:PlaceHolder runat="server" ID="PlaceHolder1"></asp:PlaceHolder>
    </table>
    <asp:DataPager ID="DataPager" runat="server" PagedControlID="CategoriesList" PageSize="3" QueryStringField="page">
      <Fields>
        //fields goes here
      </Fields>
    </asp:DataPager>
  </LayoutTemplate>
  <ItemTemplate>
    <tr><td>   //item goes here    </td></tr>
  </ItemTemplate>
</asp:ListView>

C#

protected void Page_Load(object sender, EventArgs e)
{
  if (!IsPostBack)
    {
      BindListView();
    }
}
private void BindListView()
{
  // SQL connection string, command, etc to get the data from database
  DataTable DTable = new DataTable();
  SDAdapter.Fill(DTable);
  CategoriesList.DataSource = DTable;
  CategoriesList.DataBind();
}

protected void OnPagePropertiesChanging(object sender, PagePropertiesChangingEventArgs e)
{
  (CategoriesList.FindControl("DataPager") as DataPager).SetPageProperties(e.StartRowIndex, e.MaximumRows, false);
  BindListView();
}

After deleting the an item, the data is updated by calling BindListView(); again. It works perfectly.

My problem is When there exists only one item in the last page and it is deleted, The DataPager doesn't go to the previous page. Instead it stays in the same page with no data, even no table.

How to refresh DataPager and go to prev page after the last item in the current page is deleted ?

2

There are 2 best solutions below

2
Pragnesh On
use this after your page load event

protected void Page_LoadComplete(object sender, EventArgs e)
{
  // BindListView();
}

this will work

2
skzi On

Try handling the deleted event and bind the data source from within the deleted event.

<asp:ListView ID="lv1" runat="server" OnItemDeleted="lv1_ItemDeleted"></asp:ListView>


protected void lv1_ItemDeleted(object sender, ListViewDeletedEventArgs e)
    {
        BindListView();
    }