I want to find \"Label\" control with ID = \"Label\" inside the \"ListView\" control. I was trying to do this with the following code:
((Label)this.ChatListV
Listview is a databound control; so controls inside it will have different ids for different rows. You have to first detect the row, then grab the control. Best to grab such controls is inside an event like OnItemDataBound
. There, you can do this to grab your control:
protected void myListView_ItemDataBound(object sender, ListViewItemEventArgs e)
{
if (e.Item.ItemType == ListViewItemType.DataItem)
{
var yourLabel = e.Item.FindControl("Label1") as Label;
// ...
}
}
If you want to grab it in Page_Load
, you will have to know specific row and retrieve the control as:
var theLabel = this.ChatListView.Items[<row_index>].FindControl("Label1") as Label;
This function will get Author Name from a database, you just need to call your method to get Author Name and then return it
protected string GetUserFromPost(Guid? x)
{
// call your function to get Author Name
return "User Name";
}
And to bind label in the list view you have to do it in list view 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";
}
}
Here are the list view aspx code changes (just add onitemdatabound="ChatListView_ItemDataBound"
):
asp:ListView
ID="ChatListView"
runat="server"
DataSourceID="EntityDataSourceUserPosts"
onitemdatabound="ChatListView_ItemDataBound"
It should be Label1 in the arguement:
((Label)this.ChatListView.FindControl("Label1")).Text = "active";
This should be in a databound event.
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.listview.itemdatabound.aspx
One simple solution to this problem, which avoids the FindControl
code is to place OnInit
on your label.
This would change your page code to this: <asp:Label ID="Label" runat="server" Text="" Visible="True" OnInit="Label_Init"></asp:Label>
And in your code behind you will now have a function like this:
protected void Label_Init(object sender, EventArgs e)
{
Label lblMyLabel = (Label)sender;
lblMyLabel.Text = "My Text";
}
Try it:
protected void ChatListView_ItemDataBound(object sender, ListViewItemEventArgs e)
{
if (e.Item is ListViewDataItem)
{
var yourLabel = e.Item.FindControl("Label1") as Label;
// ...
}
}