前两天刚刚搞定了DataList的嵌套绑定,结果今天用的时候就一直出问题,每次执行都找不到指定的控件,给我一个NULL的异常.(点这里看"
DataList嵌套绑定数据")
为什么找不到控件呢,使用的东西都一模一样.研究了好半天,才发现原来是一个
ListItemType的问题,上次我使用的时候,就直接用的
ItemTemplate,看代码,没有在
ItemTemplate之前再有其他的Template
Code
1
<asp:DataList ID="DataList1" runat="server"
2
Width="126px" onitemdatabound="DataList1_ItemDataBound">
3
<ItemTemplate>
4
<table style="width: 100%;">
5
<tr>
6
<td>
7
<asp:Label ID="Label1" runat="server" Text='<%# Eval("BookClassName") %>'
8
Font-Bold="True" Font-Size="16pt" ForeColor="Red"></asp:Label>
9
</td>
10
</tr>
11
<tr>
12
<td>
13
<asp:DataList ID="DataList2" runat="server" RepeatColumns="2">
14
<ItemTemplate>
15
<asp:Label ID="Label2" runat="server" Text='<%# Eval("BookClassName") %>'></asp:Label>
16
</ItemTemplate>
17
</asp:DataList>
18
</td>
19
</tr>
20
</table>
21
</ItemTemplate>
22
</asp:DataList>
所以就可以直接在代码中使用
protected
void
DataList1_ItemDataBound(
object
sender, DataListItemEventArgs e)
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
{
string f = ((Label)e.Item.FindControl("Label1")).Text;
//具体操作代码
}
结果今天用的时候,为什么总是有一个"NULL-----"异常呢,原来,我在datalist里面用了一下
HeaderTemplate,结果在
HeaderTemplate绑定数据完成时就去查找控件,这时候
ItemTemplate中的控件还没有加载,当然就找不到了.代码:
Code
1
<asp:DataList ID="dlistOut" runat="server" OnItemDataBound="dlistOut_ItemDataBound">
2
<HeaderTemplate>
3
<asp:Label ID="Label20" runat="server" Text="三、简答题(每题" Font-Bold="True"></asp:Label>
4
<%Response.Write(Session["QuestionScore"].ToString());%>
5
<asp:Label ID="Label21" runat="server" Text="分)" Font-Bold="True"></asp:Label>
6
</HeaderTemplate>
7
<ItemTemplate>
8
<table cellspacing="1" cellpadding="1" width="550" border="0" style="text-align: left">
9
<tr>
10
<td colspan="2">
11
<asp:Label ID="lblQNum" runat="server" Text='<%# Container.ItemIndex+1 %>' Font-Bold="True"></asp:Label>
12
<asp:Label ID="lblQuestion" runat="server" Text='<%# Eval("QTitle","、{0}") %>' Width="273px"
13
Font-Bold="False"></asp:Label>
14
<asp:Label ID="lblQID" runat="server" Text='<%# Eval("QID") %>'></asp:Label>
15
</td>
16
</tr>
17
</table>
18
</ItemTemplate>
19
</asp:DataList>
所以要在DataList的绑定事件中加一个判断,判断一下是否是
ItemTemplate的绑定事件,重要的就是那个
ListItemType
1
protected
void
dlistOut_ItemDataBound(
object
sender, DataListItemEventArgs e)
2
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
{
3
if(e.Item.ItemType==ListItemType.Item)
4![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
5
string qid = ((Label)e.Item.FindControl("lblQID")).Text;
6
//具体操作代码
7
}
8
}
在GridView中有点点不一样,应该用的是DataControlRowType
void
CustomersGridView_RowDataBound(Object sender, GridViewRowEventArgs e)
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
{
if(e.Row.RowType == DataControlRowType.DataRow)
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
// Display the company name in italics.
e.Row.Cells[1].Text = "<i>" + e.Row.Cells[1].Text + "</i>";
}
}