2013-02-16 126 views
2

在這段代碼中,我試圖採用ID爲「Label」的控制「標籤」,這項工作還需要從實體數據源中獲取當前的「AuthorUserID」字段我知道我可以做的這與<%# Eval("AuthorUserID" %>),但我想在代碼後面的方法這個領域,在這種情況下在「ChatListView_ItemDataBound」方法。Eval在代碼隱藏

如何在代碼後面加入當前字段(「AuthorUserID」)?

代碼隱藏:

protected void ChatListView_ItemDataBound(object sender, ListViewItemEventArgs e) 
{ 
    if (e.Item.ItemType == ListViewItemType.DataItem) 
    { 
     if (e.Item.FindControl("Label") != null) 
     { 
     } 
    } 
} 

標記:

<asp:ListView ID="ChatListView" runat="server" DataSourceID="EntityDataSourceUserPosts" OnItemDataBound="ChatListView_ItemDataBound"> 
    <ItemTemplate> 
     <div class="post"> 
      <div class="postHeader"> 
       <h2><asp:Label ID="Label1" runat="server" 
        Text= '<%# Eval("Title") + " by " + this.GetUserFromPost((Guid?)Eval("AuthorUserID")) %>' ></asp:Label></h2> 
        <asp:Label ID="Label" runat="server" Text="" Visible="True"></asp:Label> 
       <div class="dateTimePost"> 
        <%# Eval("PostDate")%> 
       </div> 
      </div> 
      <div class="postContent"> 
       <%# Eval("PostComment") %> 
      </div> 
     </div> 
    </ItemTemplate> 
</asp:ListView> 
+2

你爲什麼想通過這個?如果你只是想格式化或做一些條件 - 然後創建一個函數,如Aspx中的MyFunc,像<%#MyFunc(Eval(「PostDate」))%>,並且在代碼中寫入函數如字符串MyFunc(object dt){} – Moons 2013-02-16 08:45:19

+0

我想設置e.Item.FindControl(「標籤」)爲可見= true,如果當前記錄的用戶ID是與內容的作者ID相同。但你的想法聽起來不錯,我會嘗試。 – TheChampp 2013-02-16 08:47:29

+0

你可以在代碼後面使用'Eval(「AuthorUserID」)'',就像你在標記文件中做的那樣,如果它在'DataBound'上下文中。 – 2013-02-16 10:42:22

回答

0

根據我們的意見可能是這個代碼可以幫助

創建頁面的一些屬性,將返回說用戶名,然後

<ItemTemplate> 

    <asp:Label ID="lbl" Visible='<%# UserID == Convert.ToInt32(Eval("AuthorID")) %>' /> 

</ItemTemplate> 
0

您可以使用ListViewItemEventArgs e

protected void ChatListView_ItemDataBound(object sender, ListViewItemEventArgs e) 
    { 
     if (e.Item.ItemType == ListViewItemType.DataItem) 
     { 
      if (e.Item.FindControl("Label") != null) 
      { 
       var AuthorUserID = (string)e.Item.DataItem.e.Item.DataItem.AuthorUserID ; 
      } 
     } 
    } 

注意 我不知道,知道,如果你有界class objectdatatable如果您有界的你應該採取鑄造數據的護理數據表到達該行數據,存儲在DataItem

基本上e.Item.DataItem持有它來自數據源

欲瞭解更多信息,看看數據:

0

試試這個

添加數據關鍵是你的ListView

<asp:ListView ID="ChatListView" runat="server" OnItemDataBound="ChatListView_ItemDataBound" 
     DataKeyNames="AuthorUserID"> 

並獲得在後面的代碼

string AuthorUserID = ChatListView.DataKeys[e.Item.DataItemIndex].Value.ToString(); 
012是關鍵
3

試試這個。更改標記爲

<asp:Label ID="Label" runat="server" 
     Text="" 
     Visible='<%# CheckIfAuthorIsUser(Eval("AuthorID")) %>'> 
</asp:Label> 

而且在代碼隱藏,這樣做

protected bool CheckIfAuthorIsUser(object authorID) 
{ 
    if(authorID == null){ return false;} 
    //else compare the passed authorid parameter with the logged in userid and return the appropriate boolean value 

}