[英]ASP.net looping through table
我想知道是否有人可以幫助我? 我有一張桌子,看起來像下面這樣:
<table id="Table1" border="0">
<tr>
<td><b>1.</b> Question 1</td>
</tr><tr>
<td style="border-width:5px;border-style:solid;"></td>
</tr><tr>
<td align="left" style="width:1000px;"><input id="Radio1" type="radio" name="Group1" value="Radio1" /><label for="Radio1">Answer1</label></td>
</tr><tr>
<td align="left" style="width:1000px;"><input id="Radio1" type="radio" name="Group1" value="Radio1" /><label for="Radio1">Answer2</label></td>
</tr><tr>
<td align="left" style="width:1000px;"><input id="Radio1" type="radio" name="Group1" value="Radio1" /><label for="Radio1">Answer3</label></td>
</tr><tr>
<td align="left" style="width:1000px;"><input id="Radio1" type="radio" name="Group1" value="Radio1" /><label for="Radio1">Answer4</label></td>
</tr><tr>
<td style="height:30px;"></td>
</tr><tr>
<td><b>2.</b> Question 2</td>
</tr><tr>
<td style="border-width:5px;border-style:solid;"></td>
</tr><tr>
<td align="left" style="width:1000px;"><input id="Radio2" type="radio" name="Group2" value="Radio2" /><label for="Radio2">yes</label></td>
</tr><tr>
<td align="left" style="width:1000px;"><input id="Radio2" type="radio" name="Group2" value="Radio2" /><label for="Radio2">no</label></td>
</tr><tr>
<td style="height:30px;"></td>
</tr>
</table>
如何遍歷每組單選按鈕並獲取所選單選按鈕的文本?
上面顯示的代碼是動態創建的...在我的aspx文件中,我有以下代碼:
<asp:Table ID="Table1" runat="server">
</asp:Table>
如果要訪問ASP.NET(在服務器端)中的行,則需要將表,行和單元格轉換為服務器控件(使用runat =“ server”),並遍歷表中的控件。
編輯:: -如果以下列方式添加行,單元格和單選按鈕,它們全部將成為服務器控件(並且是runat = server),以便您可以按照我上面提到的方式訪問它們:-
// Create new row and add it to the table.
TableRow tRow = new TableRow();
table1.Rows.Add(tRow);
for (cellCtr = 1; cellCtr <= cellCnt; cellCtr++)
{
// Create a new cell and add it to the row.
TableCell tCell = new TableCell();
RadioButton rdb = new RadioButton();
rdb.ID = "rdb_" + cellCtr.ToString();
rdb.Text = "radio button";
rdb.GroupName = "rdbGroup";
tCell.Controls.Add(rdb);
tRow.Cells.Add(tCell);
}
編輯:-
您可以在每個單元格中找到控件。操作如下:-
foreach(TableCell cell in tableRow.Cells)
{
foreach(Control ctrl in cell.Controls)
{
if(ctrl is RadioButton)
{
if(ctrl.Selected)
{
string rdValue=ctrl.Text;
}
}
}
}
聽起來您好像從標記頁面的准系統<table>
開始,然后動態添加這些<input>
。
考慮采用這種方法:
runat="server"
屬性添加到表中。 <input>
標記的代碼中,添加一個新的RadioButton
控件。 在此處使用您可以稍后預測的ID。 如果選擇在邏輯上分組,也許可以改用RadioButtonList
! <tr>
和<td>
作為字符串添加。 考慮new TableRow()
和new TableCell()
。 然后使用tc.Controls.Add(myNewRadioButton);
將新的RadioButton
添加到TableCell.Controls
集合中tc.Controls.Add(myNewRadioButton);
id
引用RadioButton
控件,甚至遍歷Table1
的Controls
集合屬性即可。 foreach (Control x in Table1.Controls)
{
if (x.GetType().ToString().Equals("System.Web.UI.WebControls.RadioButton"))
{
if (((RadioButton)x).Checked)
{
//proceed.
}
}
}
將所有控件轉換為服務器控件(通過添加runat =“ server”屬性)。 然后,您可以以編程方式訪問所需的內容o。 服務器。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.