Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How To Find Checked Radio Button Using Group name My code Attached?

i am trying to find the value of checked radio using group name i have method that return it but what should i pass in that method along with group name

method is here,

private string getRadioValue(ControlCollection clts, string groupName)
{
    string ret = "";
    foreach (Control ctl in clts)
    {
        if (ctl.Controls.Count != 0)
        {
            if (ret == "")
                ret = getRadioValue(ctl.Controls, groupName);
        }

        if (ctl.ToString() == "System.Web.UI.WebControls.RadioButton")
        {
            RadioButton rb = (RadioButton)ctl;
            if (rb.GroupName == groupName && rb.Checked == true)
                ret = rb.Attributes["Value"];
        }
    }
    return ret;
}

i use it like

Oc.aProjectSubmited = getRadioValue(RadioButton,"Aps");

where Aps is radio group but getting error "invalid argument" on radio button i pass ??

hopes for your suggestion thanks in advance

like image 428
tester Joe Avatar asked Jan 29 '26 02:01

tester Joe


2 Answers

This is because you are passing RadioButton. Your method accepts ControlCollection, not a Control.

Why not pass this.Controls to pass the whole ControlCollection of the page? Or any other ControlCollection that you might be using to keep that RadioButton you want to check?

Here's an example:

    protected void Page_Load(object sender, EventArgs e)
    {
        getRadioValue(this.Controls, "Hello");
    }

    private string getRadioValue(ControlCollection clts, string groupName)
    {
        string ret = "";
        foreach (Control ctl in clts)
        {
            if (ctl.Controls.Count != 0)
            {
                if (ret == "")
                    ret = getRadioValue(ctl.Controls, groupName);
            }

            if (ctl.ToString() == "System.Web.UI.WebControls.RadioButton")
            {
                RadioButton rb = (RadioButton)ctl;
                if (rb.GroupName == groupName && rb.Checked == true)
                    ret = rb.Attributes["Value"];
            }
        }
        return ret;
    }
like image 164
aiapatag Avatar answered Jan 30 '26 14:01

aiapatag


Here's a shorter version using Linq to avoid the loops...

public static string GetRadioValue(ControlCollection controls, string groupName)
{
   var selectedRadioButton = controls.OfType<RadioButton>().FirstOrDefault(rb => rb.GroupName == groupName && rb.Checked);
   return selectedRadioButton == null ? string.Empty : selectedRadioButton.Attributes["Value"];
}
like image 27
wloescher Avatar answered Jan 30 '26 16:01

wloescher



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!