我正在研究C#和ASP.NET 4.0中的一个解决方案,我试图从我的页面中获取单选按钮的值,该页面是基于一些数据库信息动态创建的。
下面是在页面源代码中生成的内容:
<td>
<input id="masterMain_3Answer_0" type="radio" name="ctl00$masterMain$3Answer"
value="Y" onclick="return answeredyes(3);" />
<label for="masterMain_3Answer_0">Y</label>
</td>
<td>
<input id="masterMain_3Answer_1" type="radio" name="ctl00$masterMain$3Answer"
value="N" onclick="return answeredno(3,'desc');" />
<label for="masterMain_3Answer_1">N</label>
</td>在我的submit按钮的OnClick函数中,我希望根据用户的输入来选择Y或N。
以下是我到目前为止写的内容:
RadioButton _rbAnswer = new RadioButton();
RadioButtonList _rbList = new RadioButtonList();
ContentPlaceHolder cp = (ContentPlaceHolder)Master.FindControl("masterMain");
_rbAnswer = (RadioButton)Master.FindControl("masterMain_3Answer_0");
HtmlInputRadioButton rb = (HtmlInputRadioButton)Master.FindControl("masterMain_3Answer_0");
_rbAnswer = (RadioButton)cp.FindControl("masterMain_3Answer_0");
_rbList = (RadioButtonList)cp.FindControl("masterMain_3Answer_0");我可以毫无问题地获取ContentPlaceHolder,但在尝试获取后,其余对象都为空。我也尝试过删除"masterMain_“,但仍然不想找到控件。
下面是添加单个单选按钮列表的代码
TableRow _tempRow = new TableRow();
TableCell _cellOK = new TableCell();
RadioButtonList _rbList = new RadioButtonList();
_rbList.ID = r[0].ToString()+"Answer";
_rbList.RepeatDirection = RepeatDirection.Horizontal;
//add options for yes or no
ListItem _liOk = new ListItem();
_liOk.Value = "Y";
ListItem _linotOk = new ListItem();
_linotOk.Value = "N";
_rbList.Items.Add(_linotOk);
//add cell to row
_rbList.Items.Add(_liOk);
_cellOK.Controls.Add(_rbList);
_tempRow.Cells.Add(_cellOK);
//add the row to the table
stdtable.Rows.Add(_tempRow);发布于 2012-12-22 03:42:09
要快速查找动态创建的控件,请将字典添加到页面类中:
private Dictionary<string, Control> fDynamicControls = new Dictionary<string, Control>();然后,当在代码中创建新控件并为其分配ID时:
fDynamicControls.Add(newControl.ID, newControl);当你需要控件的引用时:
Control c = fDynamicControls["controlIdThatYouKnow"];发布于 2012-12-22 02:12:42
在使用FindControl时,不要使用页面生成的id。使用您在aspx中指定的ID。
如果这是在Repeateror另一个DataBound控件中,你必须首先找到当前的记录。(GridViewRow或RepeaterItem)首先,使用该项的.FindControl函数。
查看这个(不同而不是重复的)问题以查看如何执行此操作的代码示例:How to find control with in repeater on button click event and repeater is placed with in gridview in asp.net C#
发布于 2012-12-22 02:33:28
当您创建动态控制器时,为它们提供特定的ids。这便于使用我们自己的id生成控件。因此,我们可以使用此id访问控件。
还可以使用OnInit生命周期事件来生成动态控制器,这是生成它们的最佳位置。
RadioButton _rbAnswer = new RadioButton();
_rbAnswer.ID="ranswerid";https://stackoverflow.com/questions/13995124
复制相似问题