Search code examples
c#asp.netascx

How to access usercontrol's radiobuttonlist from aspx.cs file


I'm having an impossible time getting the selected value of a radiobuttonlist control from an aspx.cs file. The radiobuttonlist control is inside of an .ascx file. I keep getting the System.NullReferenceException Object reference not set to an instance of an object.

Any ideas?

I attempted to use the FindControl method several times changing it around as it would fail. Here's the last thing I tried:

protected void ClientsDropDownList_Selected(object sender, EventArgs e)
    {
        this.ConsultationFormControl.LoadClient(int.Parse(ClientsDropDownList.SelectedValue));    

            if (ClientsDropDownList.SelectedValue != "Please Select One")
            {
                UserControl US = FindControl("ConsultationFormControl") as UserControl;
                RadioButtonList rblMarStat = US.FindControl("rblMaritalStatus") as RadioButtonList;
                if (rblMarStat.SelectedValue == "Married")
                {
                    Response.Write("perfect");
                }
            }            
    }

Hope this helps.

James

Okay, guys, thanks for your help. Looks like we got it working. Thanks again, AVD. I remember creating a public property in the past for a couple of things. I just couldn't think tonight after all this coding without a break and it's late. That helped a lot. Peace, Bro. Peace fellows.


Solution

  • You can define a public property/method in user control that returns a selected value.

    EDIT:

    Add following property in user control's code behind,

    public string SelectedValue
    {
        get
        {
            return RadioButtonList1.SelectedValue;
        }
    }
    

    To access the SelectedValue property from within the .aspx page,

    string value=YourControlID1.SelectedValue;
    

    OR use FindControl method,

     RadioButtonList rad = (RadioButtonList)YourControlID1.FindControl("RadioButtonList1");
     Response.Write(rad.SelectedValue);