如何在Gridview中找到单选按钮控件

时间:2016-03-01 13:37:22

标签: asp.net vb.net gridview findcontrol

我正在尝试在gridview中找到一个radiobutton控件,但我继续为我选择的任何radiobutton获取0的输出。我想为每个单选按钮分配值1-4,然后选择任何单选按钮,它将输出到标签。

VB代码

 Dim SelectNumber As Integer

 For Each row As GridViewRow In MyGridView.Rows

        Dim radbtn1 As RadioButton = TryCast(row.FindControl("a1"), RadioButton)
        Dim radbtn2 As RadioButton = TryCast(row.FindControl("a2"), RadioButton)
        Dim radbtn3 As RadioButton = TryCast(row.FindControl("a3"), RadioButton)
        Dim radbtn4 As RadioButton = TryCast(row.FindControl("a4"), RadioButton)


        If radbtn1.Checked = True Then
            SelectNumber = 1
        ElseIf radbtn2.Checked = True Then
            SelectNumber = 2
        ElseIf radbtn3.Checked = True Then
            SelectNumber = 3
        ElseIf radbtn4.Checked = True Then
            SelectNumber = 4
        End If


    Next

    lblOutput.Text = SelectNumber

源代码

 <asp:GridView ShowHeader="false" AutoGenerateColumns="false" ID="MyGridView" runat="server" GridLines="None">
        <Columns>
            <asp:TemplateField>

                <ItemTemplate>

                    <asp:Label runat="server" ID="QuestionID" Text='<%# Eval("QuestionID")%>' />
                    <asp:Label runat="server" ID="Question" Text='<%# Eval("Question")%>' /><br />
                    <asp:RadioButton GroupName="gnA" Text='<%# Eval("a1")%>' runat="server" ID="ans1" /><br />
                    <asp:RadioButton GroupName="gnA" Text='<%# Eval("a2")%>' runat="server" ID="ans2" /><br />
                    <asp:RadioButton GroupName="gnA" Text='<%# Eval("a3")%>' runat="server" ID="ans3"  /><br />                  
                    <asp:RadioButton GroupName="gnA" Text='<%# Eval("a4")%>' runat="server" ID="ans4" /><hr />
                </ItemTemplate>
            </asp:TemplateField>

        </Columns>

    </asp:GridView>

<asp:Button ID="btnSubmit" runat="server" Text="Complete" />
   <asp:Label ID="lblOutput" runat="server" Text="" />

1 个答案:

答案 0 :(得分:1)

我很确定这个问题的原因是你在每个回发上而不是If Not Page.IsPostback数据绑定网格。然后,系统未选中任何人,SelectNumber保留默认值0

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    If Not Page.IsPostBack Then
        ' DataBind the GridView here or call a method therefore '
    End If
End Sub