简体   繁体   English

在ASP.NET应用程序中从gridview删除记录

[英]Deleting record from gridview in ASP.NET application

I have the below gridview on a page to display users with a role of "Reviewer". 我在页面上具有以下gridview,以显示具有“审阅者”角色的用户。 The grid pulls up the records correctly. 网格正确提取记录。 On the gridview is a "delete" button to remove the Reviewer role. 在gridview上是一个“删除”按钮,用于删除Reviewer角色。 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或codebehind页面上缺少某些内容,因为没有错误返回,也没有删除任何记录。

aspx control for gridview: gridview的aspx控件:

 <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. 尝试使用GridView的OnRowCommand事件来处理此问题。

In your Gridview markup : 在您的Gridview标记中

ensure OnRowCommand="GridView1_RowCommand" is present. 确保存在OnRowCommand="GridView1_RowCommand"

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". 在aspx页面上,我将OnRowDeleting和CommandName元素都设置为相同的“ DeleteRecord”值。

Changing the CommandName value to "Delete" allowed the code to be evaluated and the stored procedure to be called successfully. 将CommandName值更改为“ Delete”可以评估代码并成功调用存储过程。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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