Ram
Ram

Reputation: 691

GridView Not Updating After Updating The Database

I have a 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.

<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. I need to refresh the page or click twice to delete the row. How can I do it with one click?

Upvotes: 0

Views: 2226

Answers (3)

Ruchi
Ruchi

Reputation: 1236

Specify OnCommand Field in your linkbutton "buttonDelete"

Example :

OnCommand = "Delete_Record"

And write following code in aspx.cs

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

Upvotes: 0

Tim Schmelter
Tim Schmelter

Reputation: 460018

You just have to load the DataSource again and bind it to the GridView:

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

Upvotes: 6

muhammad kashif
muhammad kashif

Reputation: 2624

When you delete the row , rebind your grid with data.

Upvotes: 6

Related Questions