在我的网络应用程序中,datalist
位于另一个datalist
内。
我想访问datalist
。为此,我写了这段代码
DataList dl = (DataList)dlPro_Details.FindControl("dlFeatures");
但是当我尝试运行应用程序时,它会将对象引用设置为未设置为对象的实例。
然后将调试点设置为它,我发现我的object
dl是null
。
我也试过使用ItemDataBound
protected void dlPro_Details_ItemDataBound(object sender, DataListItemEventArgs e)
{
int id = 8;
string getFeatures = "";
con = new SqlConnection(str);
con.Open();
SqlCommand cmd2 = new SqlCommand("select * from Products where Pro_id=" + id + "", con);
SqlDataReader dr = cmd2.ExecuteReader();
while (dr.Read())
{
getFeatures = dr.GetValue(11).ToString();
}
string se = ",";
List<string> l1 = new List<string>();
string[] featurs = getFeatures.Split(se.ToCharArray());
for (int i = 0; i < featurs.Length; i++)
{
l1.Add(featurs[i]);
}
DataList dl = (DataList)dlPro_Details.FindControl("dlFeatures");
dl.DataSource = l1;
dl.DataBind();
}
dlPro_Details 是我的父级数据列表
这是我的完整代码
<asp:DataList ID="dlPro_Details" runat="server" OnItemDataBound="dlPro_Details_ItemDataBound">
<ItemTemplate>
<table>
<tr>
<td>
<div class="pro_img">
<asp:Image ID="proImg" runat="server" Width="230" Height="300" ImageUrl='<%#Eval("Image") %>' />
</div>
<div class="rating">
give rate<br />hello
</div>
</td>
<td style="vertical-align:top">
<div class="Pro_name">
<asp:Label ID="lbl" runat="server" Text='<%#Eval("Name") %>' Font-Bold="True"></asp:Label>
</div>
<div class="otherInfo">
<table style="width:100%;padding:8px 12px 0 12px;">
<tr>
<td>
<asp:Label ID="lblWarenty" runat="server" Text='<%#"Warranty : "+Eval("Warranty") %>'></asp:Label>
</td>
<td>
<asp:Label ID="lblBrand" runat="server" Text='<%#"By : "+Eval("Brand") %>'></asp:Label>
</td>
<td style="float:right">
Rating
</td>
</tr>
</table>
</div>
<div class="features">
<div class="feat_Head">
<asp:Label ID="lblFeatHead" runat="server" Text="Features"></asp:Label>
</div>
<div class="feat_containt">
<asp:DataList ID="dlFeatures" runat="server" RepeatColumns="5" RepeatDirection="Vertical">
<ItemTemplate>
<asp:Label ID="lblFeatures" runat="server" Text="Label"></asp:Label>
</ItemTemplate>
</asp:DataList>
</div>
</div>
</td>
</tr>
</table>
</ItemTemplate>
</asp:DataList>
答案 0 :(得分:2)
您将使用其中一个参数找到对当前项的引用,并从那里可以访问任何嵌套控件:
protected void dlPro_Details_ItemDataBound(object sender, DataListItemEventArgs e)
{
if(e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
var innerDL = e.Item.FindControl("dlFeatures") as DataList;
if(innerDL != null)
{
//do something
}
}
}