10

我有一个单选按钮列表,我需要在其中添加项目Page_Load

aspx 代码

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

后面的代码

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

控制达到后radioList.Items.Add

我不断收到Object reference not set to instance of an object 错误

我究竟做错了什么?

4

4 回答 4

21

您不需要执行 FindCONtrol。当您使用 runat="server" 属性时,只需通过名称“radio1”获取 RadioList 的引用

protected void Page_Load(object sender, EventArgs e)
{
    radio1.Items.Add(new ListItem("Apple", "1"));
}
于 2013-08-12T15:13:46.627 回答
3

通过使用

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

您不是在页面上的控件上添加列表,而是在名为 radioList 的未实例化的 Radiobuttonlist 上添加。

如果该页面可从类访问,请使用

radio1.Items.Add(new ListItem("Apple", "1"));
于 2013-08-12T15:15:36.587 回答
2

您必须添加 !ispostback

if (!IsPostBack)
    {
        radio1.Items.Add(new ListItem("Apple", "1"));
    }
于 2013-08-12T15:19:47.400 回答
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?

于 2013-11-05T20:22:13.330 回答