2010-03-21 157 views
0

即時試圖建立一個反饋表,我有一些模擬代碼類似於這樣ASP.Net單選按鈕列表

for (int i = 1; i < 3; i++) 
    { 
     TableRow tr = new TableRow(); 
     Table1.Rows.Add(tr); 
     TableCell QuestionCell = new TableCell(); 

     // get the text for the question and stick it in the cell 
     QuestionCell.Text = "<b>"+i+".</b> Question " + i; 
     tr.Cells.Add(QuestionCell); 

     TableRow tr2 = new TableRow(); 
     Table1.Rows.Add(tr2); 

     // create a cell for the choice 

     TableCell ChoicesCell = new TableCell(); 
     ChoicesCell.Width = 1000; 

     // align the choices on the left 
     ChoicesCell.HorizontalAlign = HorizontalAlign.Left; 
     tr2.Cells.Add(ChoicesCell); 

     RadioButtonList rbl = new RadioButtonList(); 
     rbl.ID = "Radio1_" + i; 
     ChoicesCell.Controls.Add(rbl); 

     rbl.Items.Add("1"); 
     rbl.Items.Add("2"); 
     rbl.Items.Add("3"); 
     rbl.Items.Add("4"); 
    } 

顯然這個代碼並不意味着什麼,它只是嘗試如何我可以做這個反饋表單,我現在遇到的問題是有一次按下了提交按鈕(表單上有一個提交按鈕),我如何瀏覽表格並從用戶選擇的單選按鈕中獲取文本?在page_load上創建的反饋!

感謝您的任何幫助!

編輯所以一旦按下按鈕

protected void Button1_Click(object sender, EventArgs e) 
{ 
    foreach (TableCell cell in Table1.Rows) 
    { 
     foreach (Control ctrl in cell.Controls) 
     { 
      if (ctrl is RadioButtonList) 
      { 
       if (ctrl.selected) // this doesnt works 
       { 
        string selected = ctrl.text // this doesnt work either 
       } 
      } 
     } 
    } 
} 

這似乎並不奏效我有這樣的代碼...我不知道我去錯了!

+0

。你什麼意思?你是否遇到特定的錯誤? – jessegavin 2010-03-21 20:40:58

回答

3

我認爲你必須在你的循環內投入Control作爲RadioButtonList

另外,嘗試當你說 '這並不適用' 使用SelectedValue屬性,而不是selected

protected void Button1_Click(object sender, EventArgs e) 
{ 
    foreach (TableCell cell in Table1.Rows) 
    { 
     foreach (Control ctrl in cell.Controls) 
     { 
      if (ctrl is RadioButtonList) 
      { 
       string selected = ((RadioButtonList)ctrl).SelectedValue; 
      } 
     } 
    } 
} 
+1

+1這絕對適用於海報。重要的是要提到.NET語言區分大小寫,並且控件的屬性(如RadioButtonList或CheckBox)不能通過基類訪問。所以,沒有'ctrl.selected'或'ctrl.Selected'這樣的東西,而是作爲'((Checkbox)ctrl).Selected',或者像你發佈的RadioButtonList那樣。 – 2010-03-21 20:52:56

0

對於這些控件,您是否具有EnableViewState = false?如果它們的ViewState設置爲false,服務器無法在回發後看到控件的用戶狀態發生了更改

0

由於您正在創建控件的方式(幾乎在實時),因此您需要重新創建這些控件Page_Init中的每個頁面請求並自行維護狀態。