简体   繁体   English

更新数据库后未更新GridView

[英]GridView Not Updating After Updating The Database

I have a GridView. 我有一个GridView。 I'm displaying all the users in the system in this GV and I have a button to Delete the user by updating the deleted column in the table to 1. 我正在此GV中显示系统中的所有用户,并且有一个按钮,可以通过将表中的已删除列更新为1来删除用户。

<asp:GridView ID="GridView1" AllowPaging="True" OnPageIndexChanging="GridView1_PageIndexChanging"
            PageSize="20" runat="server" OnRowCommand="GridView1_OnRowCommand"
            DataKeyNames="Id, Email" EnableViewState="false" AutoGenerateColumns="false">

            <Columns>
                <asp:TemplateField>
                    <ItemTemplate>
                        <asp:LinkButton ID="buttonDelete" runat="server" CommandName="Remove" Text="Delete"
                            CommandArgument='<%# Eval("Id") + ";" +Eval("Email")%>'
                            OnClientClick='return confirm("Are you sure you want to delete this user?");' />
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:BoundField DataField="FirstName" HeaderText="First Name" />
                <asp:BoundField DataField="LastName" HeaderText="Last Name" />
                <asp:BoundField DataField="Email" HeaderText="Email" />
                <asp:BoundField DataField="Status" HeaderText="Status" />
                <asp:BoundField DataField="Location" HeaderText="Location" />
            </Columns>
        </asp:GridView>

protected void GridView1_OnRowCommand(object sender, GridViewCommandEventArgs e)
{
    string cmdName = e.CommandName;
    string[] commandArgs = e.CommandArgument.ToString().Split(new char[] { ';' });
    string UserRowID = commandArgs[0];
    string Email = commandArgs[1];

    string sql = "UPDATE USERS " +
    "SET [Deleted]= 1" +
    "WHERE ROWID= " + UserRowID;

    DataTable table = PublicClass.ExeSql_Table(sql, "Utility");

    GridView1.DataBind();
}

When I click on Delete, it updates the database but it does not delete the row from the GV. 当我单击“删除”时,它会更新数据库,但不会从GV中删除该行。 I need to refresh the page or click twice to delete the row. 我需要刷新页面或单击两次以删除该行。 How can I do it with one click? 一键怎么办?

删除行时,将网格与数据重新绑定。

You just have to load the DataSource again and bind it to the GridView: 您只需要再次加载DataSource并将其绑定到GridView:

DataTable table = PublicClass.ExeSql_Table(sql, "Utility");
GridView1.DataSource = table; //  <-- you've forgotten this
GridView1.DataBind();

Specify OnCommand Field in your linkbutton "buttonDelete" 在链接按钮“ buttonDelete”中指定OnCommand字段

Example : 范例:

OnCommand = "Delete_Record"

And write following code in aspx.cs 并在aspx.cs中编写以下代码

  protected void Delete_Record(object sender, CommandEventArgs e)
{
       GridView1.DataSource = table; 
       GridView1.DataBind();    
}

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

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