How to get value of dynamic control radio button after postback

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • ive1122
    New Member
    • Jul 2009
    • 2

    How to get value of dynamic control radio button after postback

    Hi guys,

    I am looking into create a dynamic survey as posted in Get User Input From Dynamic Controls but with some different environment
    Below is what i am trying to do:
    First when the user click the button, it will populate a dynamic table with radio button for the survey questionnaire
    However, i was unable to get its value (for score calculation) after clicking the submit button
    Beside i am using an ajax extension (updatePanel) for the development
    I have been look into viewstate but i hv no idea with it.

    Does anyone have any ideas?

    Here i included some of my code:

    part of code in page
    Code:
            <asp:UpdatePanel ID="UpdatePanel1" runat="server">
                <ContentTemplate>
                    <asp:Button ID="btnTest" runat="server" Text="Take Test" OnClick="btnTest_Click" Visible="False" />
                    <asp:Label ID="lblTestErrMsg" runat="server" 
    
        ForeColor="Red"></asp:Label><br />
                        <table id="tblTest" runat="server" style="width: 100%">
                            <tr>
                                <td>
                                 <asp:PlaceHolder ID="phQuestionnaire" runat="server"></asp:PlaceHolder>
                                    <br />
                                    </td>
                            </tr>
                            <tr>
                                <td>
                                    </td>
                            </tr>
                            <tr>
                                <td>
                                    <asp:Label ID="lblResult" runat="server"></asp:Label></td>
                            </tr>
                            <tr>
                                <td>
                                </td>
                            </tr>
                        </table>
                    </ContentTemplate>
                </asp:UpdatePanel>
    Populate Dynamic Table function
    * v_dtTable and v_dtTable2 contains the data from database

    Code:
       Private Sub CreateDynamicTable(ByVal v_dtTable As Data.DataTable, ByVal v_dtTable2 As Data.DataTable)
            Me.phQuestionnaire.Controls.Clear()
            Dim cols As Integer = v_dtTable.Rows.Count + 2
            Dim rows As Integer = v_dtTable2.Rows.Count + 1
            Dim mid As Integer = v_dtTable.Rows.Count / 2
    
            Dim tbl As Table = New Table()
            tbl.ID = "tblQs"
            tbl.BorderWidth = 1
            tbl.CellPadding = 0
            tbl.CellSpacing = 0
            tbl.Width = 500
            tbl.EnableViewState = True
    
            Me.phQuestionnaire.Controls.Add(tbl)
            For i As Integer = 0 To rows - 1
                Dim tr As TableRow = New TableRow()
                Dim rowCnt As Integer = 1
                Dim colCnt As Integer = 0
    
                For j As Integer = 0 To cols - 1
                    Dim tc As TableCell = New TableCell()
                    tc.BorderWidth = 1
                    Dim lbl As Label = New Label()
                    Dim bol As Boolean = False
    
                    If i = 0 Then       
                        If j = 0 Then
                            tc.Text = "No."
    
                        ElseIf j = 1 Then
                            tc.Text = "Question"
    
                        Else
                            tc.Text = v_dtTable.Rows(j - 2).Item("scoreName")
                            tc.HorizontalAlign = HorizontalAlign.Center
                        End If
                        tc.BackColor = Drawing.Color.DeepSkyBlue
                        tc.ForeColor = Drawing.Color.White
                    Else
                        If v_dtTable2.Rows(i - 1).Item("isHeader") Then
                            bol = True
                            tc.Text = v_dtTable2.Rows(i - 1).Item("TestQuestion")
                            tc.Style("font-weight") = "bold"
    
                        ElseIf j = 0 Then
                            tc.Text = rowCnt
                            rowCnt += 1
    
                        ElseIf j = 1 Then
                            tc.Text = v_dtTable2.Rows(i - 1).Item("TestQuestion")
    
                        Else
                            Dim rBtn As RadioButton = New RadioButton
                            rBtn.GroupName = "rBtn" & rowCnt
                            rBtn.ID = "rBtn_" & rowCnt & "_" & colCnt
                            rBtn.InputAttributes("value") = v_dtTable.Rows(j - 2).Item("scoreValue")
                            colCnt += 1
                            If j = mid + 2 Then
                                rBtn.Checked = True
                            End If
    
                            tc.Controls.Add(rBtn)
                            tc.HorizontalAlign = HorizontalAlign.Center
                        End If
                    End If
    
                    If bol Then
                        tc.ColumnSpan = cols - 1
                        tr.Cells.Add(tc)
                        Exit For
                    Else
                        tr.Cells.Add(tc)
                    End If
                Next j
    
                tbl.Rows.Add(tr)                              
            Next i
    
        End Sub
    Calculate Score function
    Code:
            Private Sub subCalculateScore()
            Dim tblQs As Table = CType(Me.phQuestionnaire.FindControl("tblQs"), Table)
            Dim rb As New RadioButton
            Dim score As Integer = 0
    
            If Me.phQuestionnaire.FindControl("tblQs") Is Nothing Then
            Else
                For Each tr As TableRow In tblQs.Rows
                    For Each tc As TableCell In tr.Cells
                        For Each c As Control In tc.Controls
                            If c.GetType.ToString = rb.GetType.ToString Then
                                Dim rBtn As RadioButton = CType(c, RadioButton)
                                If rBtn.Checked Then
                                    Dim strScore As String = rBtn.InputAttributes("value")
                                    score += CInt(strScore)
                                End If
                            End If
                        Next
                    Next
                Next
            End If
    
            Me.Label1.Text = score
        End Sub
  • Frinavale
    Recognized Expert Expert
    • Oct 2006
    • 9749

    #2
    Well there are a few things to keep in mind when you're using dynamic controls.

    First of all you should consider the scope of the dynamic controls.

    If you create a control in a function (like a button, table, radiobutton...) then the control only exists within that function.....it will be rendered on the page (because you added it to the placeholder) but when the request comes back to the server the controls declared in the function will no longer exist.

    This means that dynamic controls have to have a scope for the whole page...you cannot simply declare them inside a method.

    The other thing you have to consider is the ASP Page Life Cycle....

    Please take a look this article about how to use dynamic controls in ASP.NET....


    I don't think you need to use dynamic controls for your application.
    You should be using a RadioButtonList instead of dynamically creating individual RadioButtons. You can assign a DataSource to the RadioButtonList . The RadioButtonList will automatically create the necessary RadioButtons for the DataSource that it's bound to.

    This means that your RadioButtonList is not dynamic, but the datasource that it's bound to IS....so the content of the RadioButtonList is dynamic.

    For example check out this article on how to bind a RadioButtonList to a Custom Object...if you're just using a DataBase then it's even easier :)



    This will save you a lot of problems.

    Comment

    • ive1122
      New Member
      • Jul 2009
      • 2

      #3
      Hi Frinavale.
      Thank you for your reply.

      Well, the outcome i want to get is as shown in the image below:

      I don't think that it can be done (column by column) by using radio button list.

      At first, i was using gridview to generate the survey. However, i was unable to do it using data source due to dynamic columns number. Besides, the header for the radio button is also generated dynamically. Therefore, i have no choice but to go for dynamic controls generation.

      Do you have any idea or solution for this?

      I very appreciated your help :)

      Comment

      • Frinavale
        Recognized Expert Expert
        • Oct 2006
        • 9749

        #4
        Originally posted by ive1122
        ... However, i was unable to do it using data source due to dynamic columns number. Besides, the header for the radio button is also generated dynamically. Therefore, i have no choice but to go for dynamic controls generation.
        Ah I understand, you're right, you need to use dynamic controls.

        I would recommend revisiting the GridView idea...or you could consider creating a templated control. For an example of a templated user control check out this post.

        Check out the ITemplate interface, this article about Building Templated Custom ASP.NET Server Controls, this article on working with template fields....that should probably get you started.

        If you have any questions let me know.

        -Frinny

        Comment

        • sharifee
          New Member
          • Oct 2008
          • 9

          #5
          Getting the value of Dynamic Generated RB in a GridView

          In the GridView create the the template like this


          <asp:TemplateFi eld HeaderText="Ass ign">
          <ItemTemplate >
          <input ID="Radio1" type="radio" name="RdBtn" value='<%# Eval("ID") %>' />
          </ItemTemplate>
          </asp:TemplateFie ld>



          Code Behind after post back. Get the value as below. you can get the value
          of Radio button with name. bcz in same group the name is same for each.
          and the following code will get the value of selected Radio Button

          string selectedRadioBu tton = "";
          selectedRadioBu tton = Request.Form["RdBtn"];

          Comment

          • Gaigoi
            New Member
            • Sep 2009
            • 4

            #6
            Hi,
            im working on similar project and wonder if you can help me. Can you post some sample code?

            Comment

            • sharifee
              New Member
              • Oct 2008
              • 9

              #7
              i can help you and can post sample code, when you post your Question.

              Comment

              • Gaigoi
                New Member
                • Sep 2009
                • 4

                #8
                Hi,

                I need to populate the table to display as below. All the questions and answers is store in a oracle database.

                Question | Answer 1 | Answer 2 | Answer 3 | Answer 4 | Answer 5

                How do i format so it will display as above?

                How do I loop through the radio button to find answer then insert it back to the database?

                I tried to format the question by using Response.write( ) but when I click on submit answer it does not do anything and I could not use the FindControl to find the radio button in code behind.

                Comment

                • sharifee
                  New Member
                  • Oct 2008
                  • 9

                  #9
                  i think you have two tables one for questions and other for answers .
                  if this is the case use inner join and then convert it to pivot table. you will get the desired result for formatting.

                  and for the radio button. u can do it with javascript . implement onclick event on radio button. and store the clicked radio buttons value in hidden field and get the value from hidden field in code behind. and store it to database.

                  Comment

                  • Gaigoi
                    New Member
                    • Sep 2009
                    • 4

                    #10
                    Thank you you reply. Since the question and answer are dynamic create how do i know how many hidden field to create?

                    Comment

                    • sharifee
                      New Member
                      • Oct 2008
                      • 9

                      #11
                      create only one hidden field . if u know XML then it is very easy. just write XML tags to hidden field and you can access every value or attribute of the tag you have written to hidden field.

                      Comment

                      • Gaigoi
                        New Member
                        • Sep 2009
                        • 4

                        #12
                        Thank! Im using the placeholder to solved my question.

                        Comment

                        • Frinavale
                          Recognized Expert Expert
                          • Oct 2006
                          • 9749

                          #13
                          I have no idea what your problem was, but typically you don't need to use a hidden field in order to determine the value of a radio button. A "place holder" in asp.net wouldn't really help you either since a placeholder is a container used to store server controls that are dynamically added to the Web page.

                          I'm assuming that you've solved your mysterious problem but I just wanted to make sure that whatever you've done isn't going to confuse someone else looking for help with retrieving the value of a dynamically created radio button.

                          Normally you would use the FindControl method to retrieve the dynamically created radio button (or any dynamically generated control). Once you have retrieved the dynamic control you can retrieve it's value.

                          -Frinny

                          Comment

                          Working...