当我尝试在转发器内使用转发器内的隐藏字段时
<repeater>
<repeater>
<hiddenfield>
我尝试使用此代码输入值
if (shiftrepeater.Items.Count > 0)
{
for(int shiftcount = 0 ; shiftcount<shiftrepeater.Items.Count ; shiftcount++)
{
Repeater temp = (Repeater)shiftrepeater.Items[shiftcount].FindControl("saturdayrepeater");
for (int count = 0; count < temp.Items.Count; count++)
{
DropDownList ds = (DropDownList)temp.FindControl("userdropdown");
HiddenField hf = (HiddenField)temp.FindControl("hiddenid");
SarcShiftUser user = new SarcShiftUser();
user.id = int.Parse(hf.Value);
user.workzone_id=1;
user.xdate = saturday.Text;
user.table_id = id;
user.shift_id = shiftcount+1;
user.user_id = int.Parse(ds.SelectedValue);
user.level_id= 1;
user.team_id=1;
}
}
}
asp.net代码:
<asp:Repeater ID="saturdayrepeater" runat="server" DataSourceID="saturdayrepeaterds">
<HeaderTemplate>
<table width="100%" cellpadding="0" cellspacing="0">
</HeaderTemplate>
<ItemTemplate>
<tr>
<td>
<asp:HiddenField ID="hiddenid" runat="server" Value='<%#Eval("id") %>' />
<asp:DropDownList ID="userdropdown" CssClass="select" runat="server" DataSourceID="userdropdownds" DataTextField="name" DataValueField="id" AppendDataBoundItems="true">
<asp:ListItem Text="" Value="" Selected="True"></asp:ListItem>
</asp:DropDownList>
</td></tr>
</ItemTemplate>
<FooterTemplate>
</table>
</FooterTemplate>
</asp:Repeater>
每件事都没问题......但我收到了这个错误:
对象引用未设置为对象的实例。
在这一行:
user.id = int.Parse(hf.Value);
为什么我会收到错误?
答案 0 :(得分:1)
看起来hf
为空,因为您尝试使用HiddenField
代替temp.FindControl
找到temp.Items[count].FindControl
。
更改以下内容
DropDownList ds = (DropDownList)temp.FindControl("userdropdown");
HiddenField hf = (HiddenField)temp.FindControl("hiddenid");
到这个
DropDownList ds = (DropDownList)temp.Items[count].FindControl("userdropdown");
HiddenField hf = (HiddenField)temp.Items[count].FindControl("hiddenid");
<强>更新强>
如果ds.SelectedValue
为空字符串或包含非数字字符
user.user_id = int.Parse(ds.SelectedValue);
您需要将其更改为此
int userID = 0;
if (int.TryParse(ds.SelectedValue, out userID))
{
user.user_id = userID;
}
else
{
// do something when ds.SelectedValue is non numeric
}
答案 1 :(得分:0)
试试这个
foreach (RepeaterItem items in temp.Items)
{
DropDownList ds = (DropDownList)items.FindControl("userdropdown");
HiddenField hf = (HiddenField)items.FindControl("hiddenid");
//your code
}