中继器中的ASP.NET单选按钮显示旧值

时间:2018-12-23 20:32:57

标签: asp.net

我被放置在我的中继器绑定单选按钮中,但是当用户多次单击单选按钮时,它显示的值不正确。

外观如下:

Show 7 but should 11

https://d3higte790sj35.cloudfront.net/images/kd/gm/6b5ad5669c95d5875c31d8f6d8a2c751.png

这是代码

protected void RadioButton1_CheckedChanged(object sender, System.EventArgs e)
{
    foreach (RepeaterItem item in Repeater1.Items)
    {
        RadioButton control = (RadioButton)item.FindControl("RadioButton1");

        if (control.Checked)
        {
           Label3.Text = control.Text;
        }

        ((RadioButton)item.FindControl("RadioButton1")).Checked = false;
    }

    (sender as RadioButton).Checked = true;
}


<asp:UpdatePanel ID="UpdatePanel1" runat="server">
    <ContentTemplate>
        <asp:Repeater ID="Repeater1" runat="server" DataSourceID="SqlDataSource1" OnItemDataBound="Repeater1_ItemDataBound" OnItemCommand="Repeater1_ItemCommand" >
            <ItemTemplate>   
                <asp:RadioButton ID="RadioButton1" Text='<%# Eval("ProductCode") %>' runat ="server"  GroupName="r1" OnCheckedChanged="RadioButton1_CheckedChanged" ClientIDMode="AutoID" AutoPostBack="True" Font-Size="14"  />
                <asp:Image ID="Image3" runat="server" ImageUrl='<%# Eval("Icon") %>' CssClass="ter-choce-icon" />
                <asp:Label ID="Label1" runat="server" Text='<%# Eval("Name") %>' />
            </ItemTemplate>
            <FooterTemplate>
                <br />   
                <asp:Button ID="Button2" runat="server" Text="Get One" CssClass="Get" Visible="False" CommandName="t1" />
            </FooterTemplate>
            <SeparatorTemplate><br /></SeparatorTemplate>
        </asp:Repeater>
        <asp:Label ID="Label3" runat="server" Text="Label" ></asp:Label>
    </ContentTemplate>
</asp:UpdatePanel>

2 个答案:

答案 0 :(得分:1)

您处理RadioButton事件,因此单击的按钮立即显示为sender。您唯一需要取消选中所有其他单选按钮的操作。 GroupNameRepeater中不起作用。像这样的东西。

protected void RadioButton1_CheckedChanged(object sender, EventArgs e)
{
    Label3.Text = (sender as RadioButton).Text;
    var thisItem = (sender as RadioButton).NamingContainer;
    foreach(RepeaterItem item in Repeater1.Items)
    {
        if (item != thisItem)
        {
            (item.FindControl("RadioButton1") as RadioButton).Checked = false;
        }
    }
}

答案 1 :(得分:0)

protected void RadioButton1_CheckedChanged(object sender, System.EventArgs e)
{
    foreach (RepeaterItem item in Repeater1.Items)
    {
        RadioButton control = (RadioButton)item.FindControl("RadioButton1");

        if (control.Checked)
        {
           Label3.Text = control.Text;
        }

        ((RadioButton)item.FindControl("RadioButton1")).Checked = false;
    }

    (sender as RadioButton).Checked = true;
}

在这段代码中,为什么需要这些行

 ((RadioButton)item.FindControl("RadioButton1")).Checked = false;
  (sender as RadioButton).Checked = true;

按照我的说法,单选按钮应更改其检查状态,而无需输入您的代码。 删除这些行,然后再次运行