I currently pass some values over to one of my ascx.cs files, and it displays certain radio buttons depending on the value that is sent over. The radio buttons are instantiated in the .ascx side of things:
<asp:RadioButton ID="length5yr" GroupName="SubLength" runat="server" Visible ="false"
/>
<asp:label runat="server" id="Label5yr" Visible="false" style="width: 300px">
</asp:label>
<asp:RadioButton ID="length3yr" GroupName="SubLength" runat="server" Visible ="false"
/>
<asp:label runat="server" id="Label3yr" Visible="false" style="width: 300px">
</asp:label>
<asp:RadioButton ID="length2yr" GroupName="SubLength" runat="server" Visible ="false"
/>
<asp:label runat="server" id="Labelyr2" Visible="false" style="width: 300px">
</asp:label>
<asp:RadioButton ID="length1yr" GroupName="SubLength" runat="server" Visible ="false"
/>
<asp:label runat="server" id="Label1yr" Visible="false" style="width: 300px">
</asp:label>
<asp:RadioButton ID="lengthQuarterly" GroupName="SubLength" runat="server" Visible ="false"
/>
<asp:label runat="server" id="labelQuarterly" Visible="false" style="width: 300px">
</asp:label>
<asp:RadioButton ID="lengthMonthly" GroupName="SubLength" runat="server" Visible ="false"
/>
<asp:label runat="server" id="labelMonthly" Visible="false" style="width: 300px">
</asp:label>
I want whichever radio button that ends up being the first/top one displayed to be checked. I've been able to get the last radio button checked (which also gives me other problems anyways) - but how can I get that top one checked!?
This is the code for how I determine which radio button is displayed - I have only shown one of the options just to make the code a little bit easier to read.
foreach (Dictionary<string, string> d in orderOptions)
{
if (d["length"] == "one")
{
length1yr.Visible = true;
price1yr = d["price"];
rate1yr = d["rate"];
issues1yr = d["issues"];
premium1yr = d["premium"];
Label1yr.Text = d["description"] + "<br><br>";
Label1yr.Visible = true;
SubLength1yr = "1 year";
}
For a server-side solution, the easiest would be to iterate over the list of RadioButton
and use some simple LINQ to select the first visible button.
Something like:
var buttons = new []{length5yr, ...};
var firstVisibleButton = buttons.Where(b=>b.Visible).First();
firstVisibleButton.Checked = true;
The above is probably more pseudo-code than anything, but without a full code sample, that's all I can do. I am sure you can figure out the details. The above code would have to execute after you have hidden/shown the RadioButton
.
I should probably specify that the list you create (buttons) must follow the order in which the buttons are displayed for this to work properly.