HuwD
HuwD

Reputation: 1800

find selected radio button in dynamically genereted group in C#

I have a group of radio buttons that is dynamically generated during the page load. Can't think of the best way to get the selected radio button in C#.

Any Ideas?

Upvotes: 1

Views: 1717

Answers (3)

Gerry
Gerry

Reputation: 39

Suppose you have 3 groups: Group1 has 4 variables, Group2 has 2 variables and Group3 has 3 variables.

First you need an array to store these names:

public string mygrouparray = new string[3];
mygrouparray[0] = Group1;
mygrouparray[1] = Group2;
mygrouparray[2] = Group3;

Next, you need a jagged array to store the variable names from each group:

public string[][] vararray = new string[3][];
vararray[0] = new string[4];
vararray[1] = new string[2];
vararray[2] = new string[3];

Put the variables in the vararray:

vararray[0][0] = g1var1;
vararray[0][1] = g1var2;
...
vararray[2][1] = g3var2;
vararray[2][2] = g3var3;

You also need an array to keep track of the number of variables in each group:

public int nvararray = new int[3]
nvararray[0] = 4;
nvararray[1] = 2;
nvararray[2] = 3;

As you may know, each radio button group needs a unique name. Here is how to set it up on your cshtml page:

<form method="post">
@for (int i = 0; i < 3; i++)
{
    <p><b>@Model.mygrouparray[i]</b></p>
    @for (int j = 1; j <= nvararray[i]; j++)
    {
        <p><input type="radio" [email protected]("group_", Convert.ToString(@i)) value=@j>@Model.vararray[i][j-1]</p>
    }
 }
<p><button type="submit">Submit</button></p>
</form>

The reason to start j=1 is because, if a person does not choose a radio button, it returns a value of zero.

In order to receive the chosen variables, you need an array for that:

public int varchoosearray = new int[3];

Now you can receive the variables:

for (i = 0; i < 3; i++)
{
    varchoosearray[i] = Convert.ToInt32(Request.Form[String.Concat("group_", Convert.ToString(i))])-1;
}

If a person does not choose a radio button, you will note that it will submit a value of -1 into varchoosearray and you can flag that.

Upvotes: 0

Nick
Nick

Reputation: 4212

You can use GroupName property. And then iterate through all radio buttons which are in the same GroupName to get selected one.

var checkedButton = container.Controls
                             .OfType<RadioButton>()
                             .FirstOrDefault(r => r.GroupName=="YourGroup" && r.Checked);

Upvotes: 3

Sander
Sander

Reputation: 1314

You need to be using groups, group all of the checkboxes together and then get all radiobuttons which are within the same group.

You can use a GroupName property to achieve this.

Upvotes: 0

Related Questions