所有这些都发生在同一个用户控件中,因此无法发挥作用。
<asp:Repeater ID="rptActivity" runat="server" OnItemCreated="rptActivity_ItemCreated">
<ItemTemplate>
<div class="under-label">
<div class="activity">
<%#Eval("ActivityName")%>
<input type="hidden" name="activityId" value='<%#Eval("ActivityId")%>' />
</div>
<div class="status">
<asp:DropDownList ID="ddlStatuses" DataSourceID="SqlDataSource1" DataTextField="Name" DataValueField="Id" runat="server"></asp:DropDownList>
</div>
<div class="comment">
<textarea name="comments" cols="35" rows="3" name="comment" style="float: left; margin: 0px 0px 0px 25px; font-family: Geneva, Arial, Helvetica, sans-serif;"><%#Eval("Comment")%></textarea>
</div>
</div>
</ItemTemplate>
</asp:Repeater>
我在转发器的itemcreated事件中有以下代码:
protected void rptActivity_ItemCreated(object sender, RepeaterItemEventArgs e)
{
var helper = (UpdateActivitiesHelper)e.Item.DataItem;
DropDownList ddl = (DropDownList)FindControl("ddlStatuses");
ddl.SelectedValue = helper.StatusId.ToString();
}
当我尝试使用ddl时,它会抛出NullReferenceException
。
有什么想法吗?
答案 0 :(得分:3)
由于您的下拉列表位于转发器内,因此请务必引用DataItem
以查找控件。
请确保使用e.Item.FindControl
而不是Page.FindControl
- Page.FindControl
将找不到此项目,因为它不会递归搜索该页面
protected void rptActivity_ItemCreated(object sender, RepeaterItemEventArgs e)
{
var helper = (UpdateActivitiesHelper)e.Item.DataItem;
DropDownList ddl = (DropDownList)e.Item.FindControl("ddlStatuses");
ddl.SelectedValue = helper.StatusId.ToString();
}
答案 1 :(得分:1)
尝试修改您的ItemCreated eventHandler,如下所示,看看它是否有效。
protected void rptActivity_ItemCreated(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.AlternatingItem || e.Item.ItemType == ListItemType.Item){
var helper = (UpdateActivitiesHelper)e.Item.DataItem;
DropDownList ddl = (DropDownList)e.Item.FindControl("ddlStatuses");
ddl.SelectedValue = helper.StatusId.ToString();
}
}