3

我正在使用 ASP.NET 成员资格和 Linq。我在这里有一个问题:我在具有删除按钮的网格视图中显示所有用户。看看这段代码:

<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>

和删除按钮的事件处理程序:

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

但问题是,在运行此代码并删除用户后,GridView 仍然显示该用户。

4

1 回答 1

1

发生这种情况是因为MembershipUsersLinqDataSource没有连接,如果您“刷新”UsersLinqDataSource状态然后重新绑定您的网格,所有内容都将正确显示。

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();
}
于 2012-09-10T13:34:00.353 回答