我有一个单选按钮列表,其中需要添加项目 Page_Load
aspx代码
<asp:radioButtonList ID="radio1" runat="server" RepeatLayout="Flow" RepeatDirection="Horizontal">
</asp:radioButtonList>
Run Code Online (Sandbox Code Playgroud)
代码背后
protected void Page_Load(object sender, EventArgs e)
{
RadioButtonList radioList = (RadioButtonList)Page.FindControl("radio1");
radioList.Items.Add(new ListItem("Apple", "1"));
}
Run Code Online (Sandbox Code Playgroud)
控制到达后 radioList.Items.Add
我一直在收到Object reference not set to instance of an object
错误
我究竟做错了什么?
Gui*_*gui 21
您不需要执行FindCOntrol.当您使用runat ="server"属性时,只需通过其名称"radio1"获取RadioList的引用
protected void Page_Load(object sender, EventArgs e)
{
radio1.Items.Add(new ListItem("Apple", "1"));
}
Run Code Online (Sandbox Code Playgroud)