Search code examples
asp.netgridviewupdatepanel

GridView Delete Not Re-Binding


I have a GridView with a delete template field:

<asp:UpdatePanel ID="UpdatePanel2" runat="server">
<ContentTemplate>
    <asp:GridView ID="gvCurrentDay" CssClass="gridview" OnRowCommand="gvCurrentDay_RowCommand" AutoGenerateColumns="false" runat="server">
        <Columns>
            <asp:BoundField DataField="ClientName" HeaderText="Client" />
            <asp:BoundField DataField="ProjectTitle" HeaderText="Project" />
            <asp:BoundField DataField="TimeToAdd" HeaderText="Time Allocated" HeaderStyle-HorizontalAlign="Center" ItemStyle-HorizontalAlign="Center" />
            <asp:TemplateField ItemStyle-HorizontalAlign="Center">
                <ItemTemplate>
                    <asp:ImageButton ID="imbDeleteRow" ImageUrl="~/images/icons/DeleteRed.png" CommandArgument='<%# Eval("RecordID") %>' CommandName="Delete" runat="server" />
                </ItemTemplate>
            </asp:TemplateField>
        </Columns>
    </asp:GridView>    
</ContentTemplate>

The code runs when the button is pressed and the database entry is removed from the database, but the GridView is not rebinding, here is the code that controls the delete:

protected void gvCurrentDay_RowCommand(object sender, GridViewCommandEventArgs e)
{
    if (e.CommandName == "Delete")
    {
        int RecordID = Convert.ToInt32(e.CommandArgument);

        tdl objTdl = new tdl();
        objTdl.DeleteEntryForDay(RecordID);

        GetItineryForDay(Convert.ToDateTime(txtCalendar.Text));

        lblMessages.Text = "Entry removed";
    }
}

And here is the first part of the GetItineryForDay procedure:

protected void GetItineryForDay(DateTime SelectedDate)
{
    gvCurrentDay.DataSource = null;
    gvCurrentDay.DataBind();

    tdl objTdl = new tdl();
    DataTable dt = objTdl.GetUsersProjectTimeForDay(SelectedDate, Convert.ToInt32(Request.Cookies["staffid"].Value));

    if (dt.Rows.Count > 0)
    {
        DataRow row = dt.Rows[0];
        int TotalTime2 = Convert.ToInt32(row[7]);
        string TotalTime = row[7].ToString() + " minutes";

        gvCurrentDay.DataSource = dt;
        gvCurrentDay.DataBind();

Can you see from the code any reason why the GridView is not updating? The GridView sits in an UpdatePanel.


Solution

  • Instead of using "Delete" as the CommandName, use something else, like "ManualDelete". "Delete" is usually trapped by RowDeleting and RowDeleted events.

    Alternatively, and since "the database entry is removed from the database", you could put your rebind code in the RowDeleted event.

    protected void gvCurrentDay_RowDeleted(object sender, GridViewDeletedEventArgs e)
    {
        GetItineryForDay(Convert.ToDateTime(txtCalendar.Text));
        lblMessages.Text = "Entry removed";
    }