简体   繁体   中英

Add radio button list items programmatically in 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?

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"));
}

By using

RadioButtonList radioList = (RadioButtonList)Page.FindControl("radio1");
radioList.Items.Add(new ListItem("Apple", "1"));

you are not adding your list on the control on your page, but on an un-instanciated Radiobuttonlist called radioList.

If the page is reachable from the class, use

radio1.Items.Add(new ListItem("Apple", "1"));

you must add !ispostback

if (!IsPostBack)
    {
        radio1.Items.Add(new ListItem("Apple", "1"));
    }

As an alternative to using the < asp: **> tools -
I needed to reuse a radio option which relies on a lot of jQuery integration in the site. (Also wanted to avoid just CSS hiding the content within the html code of the aspx page.)

The radio buttons needed only appear in an 'edit' page depending on security ACU level logic within the codebehind and rendered with currently stored item value data found in the db. So I used the following:

string RadioOnChk1  = (db.fieldChecked == true) ? "checked='checked'" : "";
string RadioOnChk2  = (db.fieldChecked == false) ? "checked='checked'" : "";

if (ACU > 3)
{
// Create radio buttons with pre-checked
  StringBuilder RadioButtns = new StringBuilder(); // Form input values
  {
   RadioButtns.Append("<p><label><input type=\"radio\" id=\"radiocomm1\" name=\"custmComm\" value=\"1\"");
   RadioButtns.Append(RateIncChk1 + "/>Included or </label>");
   RadioButtns.Append("<label><input type=\"radio\" id=\"radiocomm2\" name=\"custmComm\" value=\"2\"");
   RadioButtns.Append(RateIncChk2 + "/>Excluded</label>");
   RadioButtns.Append("</p>");
  }
  htmlVariable = (RadioButtns.ToString());
}

It works.. Is this a wrong way of going about it?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM