在Datalist中查找控件

时间:2010-04-01 12:20:04

标签: c# asp.net

当我尝试按下面提到的控制n数据列表时

 Error(Object reference not set to an instance of an object.

我不知道

protected void dlCategory_ItemDataBound(object sender, DataListItemEventArgs e)
    {
        Label Lb = (Label)e.Item.FindControl("LblCat");
        Lb.ForeColor = System.Drawing.Color.Red;
    }



<Datalist>
 <asp:DataList ID="dlSubCategory" runat="server" 
                                    DataSource='<%# GetSubCategory(Convert.ToString(Eval("Category_ID")))%>' 
                                    onitemcreated="dlSubCategory_ItemCreated" 
                                    onitemdatabound="dlSubCategory_ItemDataBound">
                                    <EditItemStyle ForeColor="#CC3300" />
                                    <SelectedItemStyle ForeColor="#CC3300" />
                                    <ItemTemplate>
                                        <div class="buttn_div_sub">
                                            <div class="lm40 tm2 buttn_txt">
                                                <a href='<%# Convert.ToString(Eval("ProductCategory_Id")).Insert(0,"ListView.aspx?ProductCategory_Id=") %>'
                                                    class="buttn_txt">
                                                    <asp:Label ID="Label1" runat="server" Text='<%#DataBinder.Eval(Container.DataItem,"Name") %>'></asp:Label>
                                                </a>
                                            </div>
                                        </div>
                                    </ItemTemplate>
                                </asp:DataList>
                            </ItemTemplate>

2 个答案:

答案 0 :(得分:3)

protected void dlCategory_ItemDataBound(object sender, DataListItemEventArgs e) 
{
    Label Label1 = e.Item.FindControl("Label1") as Label;
    if (LblCat != null)
    {
        string id = ((System.Data.DataRowView)e.Item.DataItem).Row["ProductCategory_Id"].ToString();

        if (Request.QueryString["ProductCategory_Id"] == id)
        {
            Label1.ForeColor = System.Drawing.Color.Red;
        }
    }
}

答案 1 :(得分:0)

你可以尝试一下吗?传递给此函数的第一个项目将是标题(如果存在于数据列表中),这就是您收到错误的原因。

protected void dlCategory_ItemDataBound(object sender, DataListItemEventArgs e) 
{
    if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
    {
        Label Lb = (Label)e.Item.FindControl("LblCat"); Lb.ForeColor = System.Drawing.Color.Red;
    }
}