2013-07-24 78 views
0

我想生成一個動態單選按鈕列表,但問題是動態列表不顯示在頁面加載。只有提交按鈕顯示。這裏是我使用的代碼:加載一個動態創建的單選按鈕列表

<asp:PlaceHolder runat="server" ID="PlaceHolder1"/> 
<asp:Button runat="server" ID="Button1" OnClick="Button1_Click" Text="Submit" /> 
<asp:Label runat="server" ID="Label1"/> 

    protected void Page_Load(object sender, EventArgs e) 
    { 
     LoadControls(); 
    } 

    protected void Button1_Click(object sender, EventArgs e) 
    { 
     var radioButtonList = PlaceHolder1.FindControl("1") as RadioButtonList; 
     Label1.Text = radioButtonList.SelectedValue; 
    } 

    private void LoadControls() 
    { 
     var tmpRBL = new RadioButtonList(); 
     tmpRBL.ID = "1"; 

     for (int i = 1; i <= 5; i++) 
     { 
      var tmpItem = new ListItem(i.ToString(), i.ToString()); 
      tmpRBL.Items.Add(tmpItem); 
     } 

     PlaceHolder1.Controls.Add(tmpRBL); 
    } 
+0

試着把它放在一個'UpdatePanel'中。 – PiLHA

+0

這段代碼應該工作得很好,確保你沒有另一個可能干擾你的'render'的'control'。 – EmmanuelRC

+0

我試過更新面板,但它並沒有解決我的問題。我沒有其他的控制,可能是互相 – user2502561

回答

0

WebForm1.aspx的

<!DOCTYPE html> 

    <html xmlns="http://www.w3.org/1999/xhtml"> 
    <head runat="server"> 
     <title></title> 
    </head> 
    <body> 
     <form id="form1" runat="server"> 
     <div> 
      <asp:PlaceHolder runat="server" ID="PlaceHolder1"/> 
      <asp:Button runat="server" ID="Button1" OnClick="Button1_Click" Text="Submit" /> 
      <asp:Label runat="server" ID="Label1"/> 
     </div> 
     </form> 
    </body> 
    </html> 

WebForm1.aspx.cs中

using System; 
    using System.Collections.Generic; 
    using System.Linq; 
    using System.Web; 
    using System.Web.UI; 
    using System.Web.UI.WebControls; 

namespace WebApplication1 
{ 
    public partial class WebForm1 : System.Web.UI.Page 
    { 
     protected void Page_Load(object sender, EventArgs e) 
     { 
      LoadControls(); 
     } 

     protected void Button1_Click(object sender, EventArgs e) 
     { 
      var radioButtonList = PlaceHolder1.FindControl("1") as RadioButtonList; 
      Label1.Text = radioButtonList.SelectedValue; 
     } 

     private void LoadControls() 
     { 
      var tmpRBL = new RadioButtonList(); 
      tmpRBL.ID = "1"; 

      for (int i = 1; i <= 5; i++) 
      { 
       var tmpItem = new ListItem(i.ToString(), i.ToString()); 
       tmpRBL.Items.Add(tmpItem); 
      } 

      PlaceHolder1.Controls.Add(tmpRBL); 
     } 
    } 
} 

它的工作原理是正確的。我希望這會有所幫助。

+0

謝謝你的答覆..問題還沒有通過使用您建議的解決方案解決了 – user2502561

+0

你在頁面上使用什麼這控制和代碼?在你的問題中沒有任何問題。 –

+0

除了上面沒有其他控件。我需要生成動態廣播列表和事件處理程序,以顯示單選按鈕列表控件的選定值 – user2502561

0

您可以定義一個空的RadioButtonList控件,然後使用Page_Load中的項目填充該控件。會有你不必手動創建它的好處。同樣使用DataBind機制,控件將您與ObjectDataSource一起提供給您更好的解決方案(ObjectDataSource的Select方法應返回項目)。

但是,除此之外,@Page指令(ASPX頁面標記中的第一行)的AutoEventWireup設置爲false。如果是這樣,則不調用Page_Load事件處理程序。該指令通常如下所示:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication1.WebForm1" %> 

我複製了代碼的其餘部分,一切都運行良好。