2012-09-09 65 views
3

我正在使用ASP.NET成員和Linq。我在這裏遇到了一個問題:我顯示了具有刪除按鈕的網格視圖內的所有用戶。看看下面的代碼:GridView DataBind不起作用

<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控件仍然顯示該用戶。

+0

你確定'Membership.DeleteUser'刪除記錄嗎?也許它將它標記爲已刪除? –

+0

@AmiramKorach:[MSDN'Membership.DeleteUser'](http://msdn.microsoft.com/en-us/library/w6b0zxdw.aspx):_「從數據庫中刪除用戶」_ –

+0

成員資格刪除用戶和如果我重新加載頁面,GridView不顯示該用戶,所以我認爲該用戶實際上被刪除。 –

回答

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(); 
}