Accessing value of dynamically created controls c# asp.net

后端 未结 2 1500
花落未央
花落未央 2021-02-04 19:32

I\'m trying to access the value of a selected radioButton. I have a list of radio button\'s seperated by sub headers (hence why i havent used a radioList)

I don\'t know

相关标签:
2条回答
  • 2021-02-04 19:43

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

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

    Hope this helps.

    0 讨论(0)
  • 2021-02-04 19:59

    Hi it sounds to me like you are bit confused over what the various properties of the radio button control do and how to generate the radio button correctly.

    The ID property is key here.

    You should set the ID property to a unique string that you then use to access the control on postback.

    The GroupName is just an alias for the standard name property of a radio button and is used so when a user clicks on a radio button in a group only one radio button 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've assigned singleType.appTypeName as the ID, assuming that this is unique.

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

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

    Now you can access the radioButton variable to check which GroupName it has, get it's value and check that it is checked.

    You will need to loop over the radio buttons to find out which one is checked. An easy way of doing this is looping over the child controls of the radioArea and checking eack control to see if it is a radio button and if it is checked. Another options is to give each ID a prefix i.e. ID="RAD_"+singleType.appTypeName and loop over the Request object and match each one with the correct suffix.

    0 讨论(0)
提交回复
热议问题