views:

8390

answers:

2

I have a Repeater control on ASPX-page defined like this:

<asp:Repeater ID="answerVariantRepeater" runat="server"
    onitemdatabound="answerVariantRepeater_ItemDataBound">
    <ItemTemplate>
        <asp:RadioButton ID="answerVariantRadioButton" runat="server"
            GroupName="answerVariants" 
            Text='<%# DataBinder.Eval(Container.DataItem, "Text")%>'"/>
    </ItemTemplate>
</asp:Repeater>

To allow select only one radio button in time I have used a trick form this article.

But now when form is submitted I want to determine which radio button is checked.

I could do this:

RadioButton checkedButton = null;

foreach (RepeaterItem item in answerVariantRepeater.Items)
{
    RadioButton control=(RadioButton)item.FindControl("answerVariantRadioButton");
    if (control.Checked)
    {
        checkedButton = control;
        break;
    }
}

but hope it could be done somehow simplier (maybe via LINQ to objects).

+3  A: 

Since You are using javascript already to handle the radio button click event on the client, you could update a hidden field with the selected value at the same time.

Your server code would then just access the selected value from the hidden field.

HectorMac
Either the original solution in your question or this will work nicely.
Kon
+1  A: 

I'm pretty sure that the only thing you could use LINQ to Objects for here would be to take the conditions from within the foreach loop and move them to a where clause.

RadioButton checked = 
    (from item in answerVariantRepeater.Items
    let radioButton = (RadioButton)item.FindControl("answerVariantRadioButton")
    where radioButton.Checked
    select radioButton).FirstOrDefault();
Kevin Gorski
Maybe it's possible to avoid using both Items and FindControl in favor of some Controls collection.
Alexander Prokofyev
I've never seen a different way to get an instance of a control from a templated parent control.The simplest thing would be to use a RadioButtonList, but I assume that your example was simplified for clarity and there were other controls in the template that prevented you from using that.
Kevin Gorski