简体   繁体   中英

Deleting record from gridview in ASP.NET application

I have the below gridview on a page to display users with a role of "Reviewer". The grid pulls up the records correctly. On the gridview is a "delete" button to remove the Reviewer role. The stored procedure that is called is working correctly when ran manually, but I seem to be missing something on the aspx or codebehind page as while no error is returned, no record is deleted either.

aspx control for gridview:

 <asp:GridView ID="GridView1" runat="server" Caption="Current Reviewers" AllowSorting="True" PagerSettings-Mode="NumericFirstLast" OnPageIndexChanging="GridView1_PageIndexChanging"
CaptionAlign="Top" EmptyDataText="No Reviewers Configured." PageSize="10" AllowPaging="true" PagerStyle-HorizontalAlign="Center" PagerStyle-Font-Size="Large"
AutoGenerateColumns="false" AlternatingRowStyle-BackColor="#cccccc" DataKeyNames="UserId" OnRowDeleting="DeleteRecord">
<Columns>

     <asp:BoundField DataField="UserId" HeaderText="Id" ItemStyle-Width="300" />
    <asp:BoundField DataField="Name" HeaderText="Name" ItemStyle-Width="250" />
    <asp:TemplateField HeaderText="Delete?">
                    <ItemTemplate>
                        <span onclick="return confirm('Are you sure to Delete the record?')">
                            <asp:LinkButton ID="lnkB" runat="Server" Text="Delete" CommandArgument='<%# Eval("UserId") %>' CommandName="DeleteRecord"></asp:LinkButton>
                        </span>
                    </ItemTemplate>
                </asp:TemplateField>
</Columns>

</asp:GridView>

Updated with full code behind:

namespace cs1.Admin
{
public partial class ReviewerMaintenance : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            BindDropDownList1();
        }
    }
    private void BindDropDownList1()
    {

        string connectionString = WebConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
        string selectSQL = String.Format("SELECT Id as UserId, FirstName + ' ' + LastName As Name from AspNetUsers where Id in(SELECT  UserId from AspNetUserRoles where RoleId = 1)");
        SqlConnection con = new SqlConnection(connectionString);
        SqlCommand cmd = new SqlCommand(selectSQL, con);
        SqlDataAdapter adapter = new SqlDataAdapter(cmd);
        DataSet ds = new DataSet();

        adapter.Fill(ds, "Reviewer");

        GridView1.DataSource = ds;
        GridView1.DataBind();
    }
    protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        GridView1.PageIndex = e.NewPageIndex;
        BindDropDownList1(); //bindgridview will get the data source and bind it again
    }

    protected void DeleteRecord(object sender, GridViewDeleteEventArgs e)
    {
        string UserId = GridView1.DataKeys[e.RowIndex].Value.ToString();
        SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["DefaultConnection"].ToString());
        SqlCommand dCmd = new SqlCommand();
        {
            conn.Open();
            dCmd.CommandText = "Reviewer_Delete";
            dCmd.CommandType = CommandType.StoredProcedure;
            dCmd.Parameters.Add("@UserId", SqlDbType.NVarChar).Value = UserId;
            dCmd.Connection = conn;
            dCmd.ExecuteNonQuery();
            // Refresh the data

            BindDropDownList1();
            dCmd.Dispose();
            conn.Close();
            conn.Dispose();

        }

    }


}
}

Try to use the OnRowCommand event of the GridView to handle this.

In your Gridview markup :

ensure OnRowCommand="GridView1_RowCommand" is present.

In your code behind :

protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
    { /* Set a breakpoint here and make sure: 
           A.) You are hitting this method 
           B.) Get value of e.CommandName */
        if (e.CommandName == "EditRecord")
        {
            // Run your edit/update logic here if needed
        }
        if (e.CommandName == "DeleteRecord")
        {
            // Delete the record here
            string UserId = GridView1.DataKeys[e.RowIndex].Value.ToString();
            SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["DefaultConnection"].ToString());
            SqlCommand dCmd = new SqlCommand();
            {
                conn.Open();
                dCmd.CommandText = "Reviewer_Delete";
                dCmd.CommandType = CommandType.StoredProcedure;
                dCmd.Parameters.Add("@UserId", SqlDbType.NVarChar).Value = UserId;
                dCmd.Connection = conn;
                dCmd.ExecuteNonQuery();
                // Refresh the data

                BindDropDownList1();
                dCmd.Dispose();
                conn.Close();
                conn.Dispose();
        }
    }

This ended up being a very simple thing. On the aspx page I had both the OnRowDeleting and CommandName elements set to the same value of "DeleteRecord".

Changing the CommandName value to "Delete" allowed the code to be evaluated and the stored procedure to be called successfully.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM