GridView DataBind不起作用

时间:2012-09-09 12:50:37

标签: asp.net linq gridview

我正在使用ASP.NET Membership和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仍会显示该用户。

1 个答案:

答案 0 :(得分: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();
}