如何在gridview中找到已选中的单选按钮?

如何找到已选中的单选按钮? 有一个带有无线电类型的hatml输入,有4个选项叫做o1 o2 o3和o4。 我可以毫无问题地访问单选按钮。 我该如何检查选择了哪个选项?

    

<asp:Label Visible="false" ID="PollIDLabel" runat="server" Text=''>
<asp:Button CommandArgument='' CommandName="foo" CssClass="btn btn-info" ID="SubmitPollButton" runat="server" Text="ثبت نظر" /> <asp:SqlDataSource ID="SelectedPollSqlDataSource" runat="server" ConnectionString="" SelectCommand="SELECT DISTINCT [PollID], [Header], [Body], [O1], [O1Vis], [O2], [O2Vis], [O3], [O1Cnt], [O2Cnt], [O3Cnt], [O3Vis], [O4], [O4Cnt], [O4Vis], [PollDate] FROM [Poll] ">

并使用此代码访问它:

 protected void SelectedPollGridView_RowCommand(object sender, GridViewCommandEventArgs e) { if (e.CommandName == "foo") { // Convert the row index stored in the CommandArgument // property to an Integer. int index = Convert.ToInt32(e.CommandArgument); // Retrieve the row that contains the button clicked // by the user from the Rows collection. GridViewRow row = SelectedPollGridView.Rows[index]; System.Web.UI.HtmlControls.HtmlInputRadioButton O1Radio = (System.Web.UI.HtmlControls.HtmlInputRadioButton)row.FindControl("O1"); System.Web.UI.HtmlControls.HtmlInputRadioButton O2Radio = (System.Web.UI.HtmlControls.HtmlInputRadioButton)row.FindControl("O2"); System.Web.UI.HtmlControls.HtmlInputRadioButton O3Radio = (System.Web.UI.HtmlControls.HtmlInputRadioButton)row.FindControl("O3"); System.Web.UI.HtmlControls.HtmlInputRadioButton O4Radio = (System.Web.UI.HtmlControls.HtmlInputRadioButton)row.FindControl("O4"); Label myPollIDLAbel = (Label)row.FindControl("PollIDLabel"); } } 

现在我该如何检查选择了哪个单选按钮?

非常感谢你。

HtmlInputRadioButton有一个属性名称Checked (返回布尔类型),你可以使用这个prop。 检查选择了哪个单选按钮。

对于示例,在RowCommand事件处理程序中获得单选按钮控件后,您必须检查prop。 像这样:

 System.Web.UI.HtmlControls.HtmlInputRadioButton O1Radio = (System.Web.UI.HtmlControls.HtmlInputRadioButton)row.FindControl("O1"); System.Web.UI.HtmlControls.HtmlInputRadioButton O2Radio = (System.Web.UI.HtmlControls.HtmlInputRadioButton)row.FindControl("O2"); System.Web.UI.HtmlControls.HtmlInputRadioButton O3Radio = (System.Web.UI.HtmlControls.HtmlInputRadioButton)row.FindControl("O3"); System.Web.UI.HtmlControls.HtmlInputRadioButton O4Radio = (System.Web.UI.HtmlControls.HtmlInputRadioButton)row.FindControl("O4"); if(O1Radio.Checked) { //O1Radio is selected. } else if(O2Radio.Checked) { //O2Radio is selected. } else if(O3Radio.Checked) { //O3Radio is selected. } else if(O4Radio.Checked) { //O4Radio is selected. } 

编辑

要对radiobuttons进行分组,您应为组中的所有radiobuttons设置相同的名称:

 ...  ...  ...  ...  ... 

有一段时间我有类似的情况,我用下面的逻辑解决了。

 for (int i = 0; i < myGrid.Rows.Count; i++) //Check if item is selected { if (((CheckBox)myGrid.Rows[i].FindControl(cbname)).Checked) //If selected { .... //Magic Happens } } 

因此,所有行都在网格中有复选框,循环遍历所有数据并检查是否选中了行。 希望能帮助到你 :)

Khizer Jalal