为什么我的中继器控件在回发时为空?
我认为这是一个“doh”时刻,因为我已经几年没有使用 dome WebForms 开发了。
我有一个中继器,其中包含一堆复选框:
<asp:Repeater EnableViewState="true" ID="IDTypesRepeater" runat="server" OnItemDataBound="IdTypesRepeaterItemDataBound">
<HeaderTemplate/>
<ItemTemplate>
<asp:CheckBox EnableViewState="true" ID="chkIdType" Text="<%# ((KeyValuePair<string,int>)Container.DataItem).Key %>" runat="server" />
<asp:HiddenField ID="idType" Value="<%# ((KeyValuePair<string,int>)Container.DataItem).Value %>" runat="server"/>
<br />
</ItemTemplate>
</asp:Repeater>
我需要获取在后面的代码中选择的复选框:
foreach (RepeaterItem repeaterItem in IDTypesRepeater.Items)
{
if ( ((CheckBox)repeaterItem.FindControl("chkIdType")).Checked )
{
// Do something
}
}
但是在回发时,此代码不起作用!我知道总是对转发器进行数据绑定,所以我这样做了:
protected void Page_Load(object sender, EventArgs e)
{
IDTypesRepeater.DataSource = DocTemplateHelper.GetApplicableIDTypes().Where(type => type.Value != 0);
IDTypesRepeater.DataBind();
}
所以这会重新填充转发器,但更新代码永远找不到任何选中的复选框..有什么想法吗?
I think this is a "doh" moment caused by me not having dome WebForms dev for a few years..
I have a repeater which which contains a bunch of checkboxes:
<asp:Repeater EnableViewState="true" ID="IDTypesRepeater" runat="server" OnItemDataBound="IdTypesRepeaterItemDataBound">
<HeaderTemplate/>
<ItemTemplate>
<asp:CheckBox EnableViewState="true" ID="chkIdType" Text="<%# ((KeyValuePair<string,int>)Container.DataItem).Key %>" runat="server" />
<asp:HiddenField ID="idType" Value="<%# ((KeyValuePair<string,int>)Container.DataItem).Value %>" runat="server"/>
<br />
</ItemTemplate>
</asp:Repeater>
I need to get the checkboxes that are selected in the code behind:
foreach (RepeaterItem repeaterItem in IDTypesRepeater.Items)
{
if ( ((CheckBox)repeaterItem.FindControl("chkIdType")).Checked )
{
// Do something
}
}
But on postback, this code isn't working! I know about always databinding a repeater, so I've done this:
protected void Page_Load(object sender, EventArgs e)
{
IDTypesRepeater.DataSource = DocTemplateHelper.GetApplicableIDTypes().Where(type => type.Value != 0);
IDTypesRepeater.DataBind();
}
So this repopulates the repeater, but the Update code never finds any checked checkboxes.. Any ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在Page_Init事件中绑定
Bind in the Page_Init event
请务必在页面加载中使用
!Page.IsPostBack
方法。否则,中继器将不断重置,并且所有复选框
将在那里默认值(未选中)
Be sure to use the
!Page.IsPostBack
method in your pageload.Otherwise, the Repeater will keep getting reset, and all your checkboxes
will be in there default value (unchecked)
这应该可以解决它。您将控件绑定到回发,因此丢失了值。您可以在处理任何事件后绑定它以显示更新的记录。
This should fix it. You are binding the control on postback hence losing the values. You can bind it after handling any event to show the updated record.