在ListView控件中查找控件
我想在“ListView”控件中找到ID =“Label”的“Label”控件。 我试图使用以下代码执行此操作:
((Label)this.ChatListView.FindControl("Label")).Text = "active";
但我得到此exception: 对象引用未设置为对象的实例 。
这有什么不对?
这是aspx代码:
<asp:Label ID="Label1" runat="server" Text= '' >
Listview是一个数据绑定控件; 因此,它内部的控件将具有不同行的不同ID。 您必须首先检测该行,然后获取控件。 最好抓住这样的控件是在像OnItemDataBound
这样的事件中。 在那里,你可以这样做来抓住你的控制:
protected void myListView_ItemDataBound(object sender, ListViewItemEventArgs e) { if (e.Item.ItemType == ListViewItemType.DataItem) { var yourLabel = e.Item.FindControl("Label1") as Label; // ... } }
如果要在Page_Load
抓取它,则必须知道特定行并将控件检索为:
var theLabel = this.ChatListView.Items[].FindControl("Label1") as Label;
它应该是争论中的Label1:
((Label)this.ChatListView.FindControl("Label1")).Text = "active";
这应该是数据绑定事件。
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.listview.itemdatabound.aspx
此函数将从数据库中获取作者名称,您只需调用您的方法获取作者名称,然后将其返回
protected string GetUserFromPost(Guid? x) { // call your function to get Author Name return "User Name"; }
要在列表视图中绑定标签,您必须在列表视图ItemDataBound
Event中执行此操作
protected void ChatListView_ItemDataBound(object sender, ListViewItemEventArgs e) { if (e.Item.ItemType == ListViewItemType.DataItem) { Label lbl = e.Item.FindControl("Label") as Label; lbl.Text = "Active"; } }
以下是aspx代码更改的列表视图(只需添加onitemdatabound="ChatListView_ItemDataBound"
):
asp:ListView ID="ChatListView" runat="server" DataSourceID="EntityDataSourceUserPosts" onitemdatabound="ChatListView_ItemDataBound"
避免FindControl
代码的一个简单的解决方案就是在标签上放置OnInit
。
这会将您的页面代码更改为:
在您的代码中,您现在将拥有如下函数:
protected void Label_Init(object sender, EventArgs e) { Label lblMyLabel = (Label)sender; lblMyLabel.Text = "My Text"; }
试试吧:
protected void ChatListView_ItemDataBound(object sender, ListViewItemEventArgs e) { if (e.Item is ListViewDataItem) { var yourLabel = e.Item.FindControl("Label1") as Label; // ... } }