Access dynamically generated C # asp.net controls

I am trying to access the value of the selected radioButton. I have a list of radio buttons separated by sub headers (hence why I did not use radioList)

I don’t know how to access the selected value, since I’m not sure what name it gave, being dynamic.

The following code is in a for loop and displays the radio parameters. All parameters are intended for one required user selection.

//add list to radio button list RadioButton button1 = new RadioButton { GroupName = "myGroup", Text = singleType.appTypeName, ID = singleType.appTypeID.ToString() }; radioArea.Controls.Add(button1); myLabel = new Label(); myLabel.Text = "<br />"; radioArea.Controls.Add(myLabel); 

This is how I try to access it:

 RadioButton myButton = (RadioButton) radioArea.FindControl("myGroup"); 

I understand that this should be very simple, but I still have a very deep understanding of PHP and appreciate any help.

thanks

+6
c # dynamic controls
source share
2 answers

Hi, this sounds to me as if you are a little confused by what the various properties of the radio button control do and how to create the radio button correctly.

The ID property here is the key.

You must set a unique string for the ID property, which you then use to access the control in the postback.

GroupName is just an alias for the standard property of the switch name and is used when a user clicks on a switch in a group, only one radio book can be selected.

For example:

 //add list to radio button list RadioButton radioButton = new RadioButton(); radioButton.GroupName = "radioGroup"; radioButton.Text = singleType.appTypeID.ToString(); radioButton.ID = singleType.appTypeName; radioArea.Controls.Add(radioButton); Label label = new Label(); label.Text = "<br />"; radioArea.Controls.Add(label); 

In the above example, I assigned singleType.appTypeName as an identifier, considering it to be unique.

Then, to extract the value in postback, do this, assumnig that singleType.appTypeName = "mySuperApp":

 RadioButton radioButton = (RadioButton) radioArea.FindControl("mySuperApp"); 

Now you can access the radioButton variable to check which one belongs to GroupName, get it and check that it is checked.

You will need to flip the switches to see which one is installed. An easy way to do this is to iterate over the radioArea child controls and check the eack control to see if it is a switch, and if it is installed. Other parameters are to provide each identifier with a prefix ie ID = "RAD _" + singleType.appTypeName and a loop over the Request object and match each of them with the correct suffix.

+9
source share

The FindControl method that you use expects you to pass it the ID that was assigned to control when it was created.

So, for your example, RadioButton.ID should be equal to singleType.appTypeID.ToString()

Hope this helps.

+3
source share

All Articles