Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GridView DataBind does not work

I am using ASP.NET Membership and Linq. I have a problem here: I show all users inside a grid view that has a delete button. Take a look at this code:

<asp:GridView 
    ID="UsersGridView" 
    runat="server" 
    AutoGenerateColumns="False" 
    DataSourceID="UsersLinqDataSource" 
    AllowPaging="True">

    <Columns>
        <asp:BoundField DataField="UserName" HeaderText="UserName" ReadOnly="True" SortExpression="UserName" />
        <asp:BoundField DataField="LastActivityDate" HeaderText="LastActivityDate" ReadOnly="True" SortExpression="LastActivityDate" />
        <asp:TemplateField>
            <ItemTemplate>
                <asp:Button ID="DeleteButton" runat="server" CommandArgument='<%# Eval("UserName") %>' Text="Delete" OnClick="DeleteButton_Click"/>
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>

<asp:LinqDataSource 
    ID="UsersLinqDataSource" 
    runat="server" 
    ContextTypeName="TraceWeb.DataModel.DataContextDataContext" 
    EntityTypeName="" 
    Select="new (UserName, LastActivityDate)" 
    TableName="Users" 
    EnableDelete="True">
</asp:LinqDataSource>

And Delete button's event handler:

protected void DeleteButton_Click(object sender, EventArgs e)
{
    String username = (String)((sender as IButtonControl).CommandArgument);
    Membership.DeleteUser(username, true);
    UsersGridView.DataBind();
}

But problem is that after running this code and deleting a user, GridView still shows that user.

like image 234
Ali Behzadian Nejad Avatar asked Jul 22 '26 17:07

Ali Behzadian Nejad


1 Answers

This happens because Membership and UsersLinqDataSource are not connected and if you "refresh" the UsersLinqDataSource status and then rebind your grid, all will be displayed properly.

protected void DeleteButton_Click(object sender, EventArgs e)
{
    String username = (String)((sender as IButtonControl).CommandArgument);
    Membership.DeleteUser(username, true);

    // first solution: may not work properly
    UsersLinqDataSource = yourLinqData;

    // second solution: work
    UsersLinqDataSource = null;
    UsersLinqDataSource = yourLinqData;

    UsersGridView.DataBind();
}

Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!