在ASP.NET中,要動態地向RadioButtonList控件添加選項,您可以使用以下方法:
<asp:RadioButtonList ID="RadioButtonList1" runat="server"></asp:RadioButtonList>
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
for (int i = 1; i <= 5; i++)
{
ListItem listItem = new ListItem();
listItem.Text = i.ToString();
listItem.Value = i.ToString();
RadioButtonList1.Items.Add(listItem);
}
}
}
在這個示例中,我們首先檢查頁面是否處于首次加載狀態(!IsPostBack),以避免在回發時重復添加列表項。然后,我們使用一個for循環來創建列表項,并將它們添加到RadioButtonList控件中。每個列表項的文本和值都設置為循環變量i的值。
這樣,當頁面加載時,RadioButtonList控件就會顯示數字1到5的選項。您可以根據需要修改循環和列表項的內容來添加其他選項。