Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
245 views
in Technique[技术] by (71.8m points)

c# - Find Control Inside ListView Control

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.ChatListView.FindControl("Label")).Text = "active";

But I am getting this exception: Object reference not set to an instance of an object .

What is wrong here ?

This is aspx code:

<asp:ListView ID="ChatListView" runat="server" DataSourceID="EntityDataSourceUserPosts">
    <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>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...