Bhakti
Bhakti

Reputation: 41

GridView not refreshing after Delete event

I am having a strange problem with asp.net GridView. I have GridView that is bound to a LinqDataSource. On GridView's row deleting event, I am deleting the row from database, but the grid is not refreshed, (even after BINDING to the datasource).

When I put a breakpoint, I could see the OnRowDeleting event is fired after the LinqDS_Selecting event. But its not fired again after the delete event! Could that be the reason? What am I doing wrong?

Could some one please help. Many thanks in Advance.

.aspx file:

<asp:LinqDataSource
    ID="LinqDS"
    runat="server"
    OnSelecting="LinqDS_Selecting">
</asp:LinqDataSource>

<asp:GridView
    DataSourceID = "LinqDS"
    ID = "gv1"
    runat = "server"  
    DataKeyNames = "InstructionId"
    EnableViewState = "false"
    OnRowDataBound = "gv1_RowDataBound" 
    OnRowDeleting = "gv1_RowDeleting" 
    OnRowCommand = "gv1_RowCommand"
    PageSize = "30" >
    <Columns>
        <!-- My colums --->
    </Columns>
</asp:GridView>

.aspx.cs

protected void Page_Load(object sender, EventArgs e)
{

}

protected void LinqDS_Selecting(object sender, LinqDataSourceSelectEventArgs e)
{
    // my linq to sql query
    var query = from  .... .... ;
    e.Result = query;
}

protected void gv1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
    int instructionId = (int)gv1.DataKeys[e.RowIndex].Value;
    /// my delete logic
    CTX.SubmitChanges();
    gv1.DataBind();
}

Upvotes: 4

Views: 5478

Answers (4)

Ed Sansbury
Ed Sansbury

Reputation: 96

I normally specify a 'DeleteMethod' on the ObjectDataSource (LinqDataSource in your case).

    <asp:ObjectDataSource ID="odsInsurerGroupAssignedLogins" runat="server" OldValuesParameterFormatString="{0}"
        TypeName="acg.BusinessLogic.InsurerGroupAssignedLogins"
        SelectMethod="GetInsurerGroupAssignedLogins"
        DeleteMethod="Delete"
        EnablePaging="true"
        StartRowIndexParameterName="startRowIndex"
        MaximumRowsParameterName="maximumRows"
        SelectCountMethod="GetInsurerGroupAssignedLogins_RowCount"
        SortParameterName="sortExpression">
        <SelectParameters>
            <asp:ControlParameter Name="insuranceCompanyGroupID" ControlID="ddlInsuranceCompanyGroupID" PropertyName="Text" Type="Int32" />
            <asp:ControlParameter Name="loginID" ControlID="ddlLoginID" PropertyName="Text" Type="Int32" />
        </SelectParameters>
    </asp:ObjectDataSource>

Here is the delete button.

<asp:TemplateField ShowHeader="False">
    <ItemTemplate>
        <asp:ImageButton ID="btnDelete" ImageAlign="Middle" runat="server" ImageUrl="~/MediaFiles/DeleteOut.png"
            AlternateText="Delete" CommandName="Delete" CausesValidation="false" ValidationGroup="Error"
            OnClientClick="return confirm('Are you sure you want to delete this record?');" CssClass="btnDelete" />
    </ItemTemplate>
    <ItemStyle CssClass="LastCol" />
</asp:TemplateField>

Then maybe something like the following in the code behind.

Private Sub odsInsurerGroupAssignedLogins_Deleted(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.ObjectDataSourceStatusEventArgs) Handles odsInsurerGroupAssignedLogins.Deleted
    If e.Exception Is Nothing Then

        Select Case Convert.ToInt32(e.ReturnValue, System.Globalization.CultureInfo.CurrentCulture.NumberFormat)
            Case 0
                WarningMessagePanel.Visible = False

                SuccessMessagePanel.Visible = True
                SuccessMessage.Text = String.Format("<b>{0}</b><br /><br /><i>{1}</i>", ConfigurationManager.AppSettings("AdminSuccessMessage"), ConfigurationManager.AppSettings("DeleteSuccess"))

            Case -1
                SuccessMessagePanel.Visible = False

                WarningMessagePanel.Visible = True
                WarningMessage.Text = String.Format("<b>{0}</b><br /><br /><i>{1}</i>", ConfigurationManager.AppSettings("AdminErrorMessage"), ConfigurationManager.AppSettings("DeleteError"))

            Case Else
                SuccessMessagePanel.Visible = False

                WarningMessagePanel.Visible = True
                WarningMessage.Text = String.Format("<b>{0}</b><br /><br /><i>ERROR: The data could not be deleted</i>", ConfigurationManager.AppSettings("AdminErrorMessage"))

        End Select

    Else
        SuccessMessagePanel.Visible = False
        WarningMessagePanel.Visible = True
        WarningMessage.Text = GetDelException(e)
        e.ExceptionHandled = True
    End If

Upvotes: 0

R Singh
R Singh

Reputation: 65

I can't point out error in your code but I am giving you my code which i did to delete the data.

<asp:GridView ID="GridView1" runat="server" OnRowDeleting="Del" DataKeyNames="Clg_ID" BackColor="#DEBA84" 
                BorderColor="#DEBA84" BorderStyle="None" BorderWidth="1px" CellPadding="3" 
                CellSpacing="2">
                <Columns>
                    <asp:CommandField ShowDeleteButton="True" />
                </Columns>
                <FooterStyle BackColor="#F7DFB5" ForeColor="#8C4510" />
                <HeaderStyle BackColor="#A55129" Font-Bold="True" ForeColor="White" />
                <PagerStyle ForeColor="#8C4510" HorizontalAlign="Center" />
                <RowStyle BackColor="#FFF7E7" ForeColor="#8C4510" />
                <SelectedRowStyle BackColor="#738A9C" Font-Bold="True" ForeColor="White" />
                <SortedAscendingCellStyle BackColor="#FFF1D4" />
                <SortedAscendingHeaderStyle BackColor="#B95C30" />
                <SortedDescendingCellStyle BackColor="#F1E5CE" />
                <SortedDescendingHeaderStyle BackColor="#93451F" />
            </asp:GridView>

.cs file

protected void Del(object sender, GridViewDeleteEventArgs e)
    {
        string i = GridView1.DataKeys[0].Value.ToString();
        SqlConnection cn = new SqlConnection();
        cn.ConnectionString = ConfigurationManager.ConnectionStrings["cn"].ConnectionString.ToString();
        cn.Open();
        SqlCommand cmd = new SqlCommand("Delete from Feedback where Clg_ID='" + i + "'", cn);
        cmd.ExecuteNonQuery();
        cmd.Dispose();
        cn.Close();
        Response.Redirect("MFeedback.aspx");
    }

Upvotes: 1

chead23
chead23

Reputation: 1879

If your record is actually deleted correctly and the grid is simply just not showing the changes I would try and put the GridView inside an UpdatePanel and see if this helps.

<asp:UpdatePanel runat="server" UpdateMode="Always">
    <ContentTemplate>
        // GridView
    </ContentTemplate>
</asp:UpdatePanel>

Upvotes: 1

adripanico
adripanico

Reputation: 1058

Try setting the EditIndex of the GridView to -1 on the ItemDeleting method of the GridView :

protected void gv1_RowDeleting(object sender, GridViewDeleteEventArgs e) {
    gv1.EditIndex = -1;
    gv1.DataBind();
}

and moving your delete logic to the RowCommand method of the GridView:

protected void gv1_RowCommand(object sender, GridViewDeleteEventArgs e) {
    If (e.CommandName == "Delete") {
        int instructionId = (int) gv1.DataKeys[e.RowIndex].Value;
        /// my delete logic
        CTX.SubmitChanges();
    }
}

Your control for the delete action should be something like:

<asp:LinkButton ID="lbDel" runat="server" Text="Delete" CommandName="Delete" />

Upvotes: 0

Related Questions