Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add radio button list items programmatically in asp.net

Tags:

c#

asp.net

I have a radio button list whose items I need to add on Page_Load

aspx code

<asp:radioButtonList ID="radio1" runat="server" RepeatLayout="Flow" RepeatDirection="Horizontal">
</asp:radioButtonList>

code behind

protected void Page_Load(object sender, EventArgs e)
{
    RadioButtonList radioList = (RadioButtonList)Page.FindControl("radio1");
    radioList.Items.Add(new ListItem("Apple", "1"));
}

After the control reaches radioList.Items.Add

I keep getting the Object reference not set to instance of an object error

What am I doing wrong?

like image 563
user544079 Avatar asked Aug 12 '13 15:08

user544079


People also ask

What is the difference between radio button and radio button list in asp net?

An asp:radiobuttonlist creates a group of radiobuttons that ensures when one is selected, the others are deselected whereas asp:radiobutton is not within a group and therefore cannot be deselected by clicking other radio buttons.

How do you check whether a RadioButton is checked or not in asp net?

Use document. getElementById('id'). checked method to check whether the element with selected id is check or not.


1 Answers

You don't need to to do a FindCOntrol. As you used the runat="server" attributes, just get the reference of your RadioList via its name "radio1"

protected void Page_Load(object sender, EventArgs e)
{
    radio1.Items.Add(new ListItem("Apple", "1"));
}
like image 172
Guigui Avatar answered Oct 20 '22 19:10

Guigui