locked
Validation of dinamically created checkbox RRS feed

  • Question

  • User1877874361 posted

    Hello, 

    I've populated a checkbox list dynamically from a database . before submit my form I want to validate at least one checkbox checked for each group. For this I'm using Custom field Validatos both Requiered Field Validator but it doesn't work on submit.

    The code I'm using is as follows:

      Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    ...................
    
                                Dim n As Integer = 0
                                Do While sdr02.Read
                                    n = n + 1
                                    '1º.- creamos objeto checkbox
                                    ' Panel3.Controls.Add(New LiteralControl("  "))
                                    Dim chkpregunta As New CheckBoxList
                                    chkpregunta.ID = sdr02(0) + n
                                    chkpregunta.Items.Add(Trim(sdr02(2)))
                                    Panel3.Controls.Add(chkpregunta)
    
                                Loop
                                'validación
                                Dim chkValidator As New RequiredFieldValidator
                                chkValidator.ControlToValidate = chkpregunta
                                chkValidator.ErrorMessage = "Debes de seleccionar al menos una opción para " + Trim(sdr02(2))
                                chkValidator.ValidationGroup = "chkPreguntas"
                                chkValidator.ID = vectorId(0) & "--" & sdr02(0)
                                chkValidator.SetFocusOnError = True
                                Panel3.Controls.Add(chkValidator)
                                'validación fin
    
    
                            Catch ex As Exception
    
                            End Try
                           .........................................
    
        End Sub

    If someone could give me an orientation of what I'm doing wrong it will be much appreciated

    thanks

    Monday, August 27, 2018 10:37 AM

Answers

  • User-1171043462 posted

    Why you need to create a Dynamic Validator and dynamic CheckBoxList?

    Just pass data from database to CheckBoxList and it will generate CheckBoxes

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, August 28, 2018 10:30 AM
  • User475983607 posted

    I don't get it.  The code shown is looping over a collection and creating server controls manually.  Rather than manually rendering server controls, simply assign the data source to the data bound control. 

    Users are isolated from one another in web applications.  Can you explain why the number of users and each user selection can affect the other users and how this dictates that the controls must be created manually?  It just does not make sense.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, August 28, 2018 11:19 AM

All replies

  • User475983607 posted

    If someone could give me an orientation of what I'm doing wrong it will be much appreciated

    Dynamic controls must be recreated early in the page life cycle, otherwise the framework has no idea the controls exist when page state is stood up.  This particular question is ask often over many years and there is a lot of information about creating dynamic controls that a simple Internet search will turn up.

    I recommend that you use standard Web Forms patterns and rather than creating checkboxes use a data bound control like a checkbox.

    IF you must use dynamic controls then yo must write code to recreate the controls on the Page_Init or Page_load events.

    Monday, August 27, 2018 11:04 AM
  • User1877874361 posted

    thanks for answering Mgebhard,

    I'll give a round at all.

    best regards

    Monday, August 27, 2018 11:33 AM
  • User-1171043462 posted

    If you want dynamic CheckBoxes from Database go for a CheckBoxList control

    Bind CheckBoxList from Database in ASP.Net - ASPSnippets

    And for At Least one checked refer

    Validate ASP.Net CheckBoxList (at least one CheckBox checked ...

    Monday, August 27, 2018 3:32 PM
  • User1877874361 posted

    Hi Mudassar, thanks for your answer.

    Your code is always pretty fine, but in this case I don't know the exactly number of checkboxes as the user choose previously the options, so the number of checkboxes to validate is always variable.

    that is the reason to create them in code behind. In a previous webform user can choose a number of options from a listbox. After this, I show him a number of options based on this selection.

    For your clarity the code for the first webform is as follows:

     <asp:listbox ID="ddlcompetencias" runat="server" DataSourceID="SqlDataSource3"  SelectionMode ="Multiple"
                   DataTextField="Competencia" DataValueField = "KeyComp" AppendDataBoundItems = "true" Height="224px" Width="244px" CssClass="NormalBold">
                                        
                        </asp:listbox>
    
        <asp:RequiredFieldValidator ID="rfvCompetencias" ControlToValidate="ddlcompetencias" InitialValue="" 
            runat="server" ErrorMessage="al menos una competencia obligatorio" ValidationGroup="excPlantilla"></asp:RequiredFieldValidator>
    
    
    
         <asp:SqlDataSource ID="SqlDataSource3" runat="server" ConnectionString="<%$ ConnectionStrings:oConn %>"
                            SelectCommand="usp_Competencias_SELECT" SelectCommandType ="StoredProcedure">
                        </asp:SqlDataSource>

    user choose one or more options from this Listbox. Once the form has been submitted, I bind a template from previous options from a database where I show user possible options for each one oh the previous selected.

    The complete code in this case is as follows: (I cannot insert a screenshot in this space, sorry)

      Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    
            lblNT.Text = Session("nt")
            lblOficina.Text = Request.Form("ddlOficina")
                lblCliente.Text = Request.Form("ddlclientes")
                lblPuesto.Text = Request.Form("ddlPuesto")
                lblFecha.Text = DateTime.Now
                'carga de campos ocultos
                hidecliente.Value = lblCliente.Text
                hident.Value = lblNT.Text
                hidepuesto.Value = lblPuesto.Text
                hideOficina.Value = lblOficina.Text
    
    
    
                'desglosamos competencias con coma
                Dim vectorComp = Split(Request.Form("ddlCompetencias"), ",")
    
                'separamos la competencia de su id
                For i = 0 To UBound(vectorComp) 'RECORREMOS EL VECTOR
                    Dim vectorId = Split(vectorComp(i), "-")
    
    
    
    
    
                    'Consulta para capturar la descripción de cada Competencia
                    Dim Conn1 As New SqlConnection
                    Conn1.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings("oConn").ConnectionString
                    Dim cmd01 As SqlCommand = New SqlCommand
                    cmd01.CommandText = "usp_Competencias_GET"
                    cmd01.CommandType = CommandType.StoredProcedure
                    cmd01.Connection = Conn1
                    Conn1.Open()
                    cmd01.Parameters.Add("@pIdComp", SqlDbType.Int).Value = vectorId(0)
                    Dim sdr01 As SqlDataReader = cmd01.ExecuteReader
                    Try
    
    
                        Do While sdr01.Read
                            'etiqueta nombre competencia
                            Dim lblCompetencia As New Label
                            lblCompetencia.Text = vectorId(1)
                            lblCompetencia.ID = vectorId(0)
                            lblCompetencia.CssClass = "NormalBold"
                            Panel3.Controls.Add(lblCompetencia)
    
    
                            Panel3.Controls.Add(New LiteralControl("<br />"))
                            Panel3.Controls.Add(New LiteralControl("<hr />"))
                            'etiqueta descripción competencia
                            Dim lblCompetenciaDesc As New Label
                            Dim lbltextodesc As New Label
                            lbltextodesc.Text = "Descripción :"
                            Panel3.Controls.Add(lbltextodesc)
                            lblCompetenciaDesc.Text = sdr01(0)
                            lblCompetenciaDesc.CssClass = "normalbold"
                            Panel3.Controls.Add(lblCompetenciaDesc)
                            Panel3.Controls.Add(New LiteralControl("<br />"))
                            Panel3.Controls.Add(New LiteralControl("<br />"))
                            Panel3.Controls.Add(New LiteralControl("<br />"))
    
                            '*****************************************************
                            'agregamos opciones de pregunta para cada competencia
                            '*****************************************************
                            'campo clave de búsqueda = vectorid(0) anterior
                            Dim Conn2 As New SqlConnection
                            Conn2.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings("oConn").ConnectionString
                            Dim cmd02 As SqlCommand = New SqlCommand
                            cmd02.CommandText = "usp_Preguntas_x_Comp_GET"
                            cmd02.Parameters.Add("@pIdComp", SqlDbType.Int).Value = vectorId(0)
                            cmd02.CommandType = CommandType.StoredProcedure
                            cmd02.Connection = Conn2
                            Conn2.Open()
                            Dim sdr02 As SqlDataReader = cmd02.ExecuteReader
    
                            Try
    
    
                                Dim n As Integer = 0
                                Do While sdr02.Read
                                    n = n + 1
                                    '1º.- creamos objeto checkbox
                                    ' Panel3.Controls.Add(New LiteralControl("&nbsp;&nbsp;"))
                                    Dim chkpregunta As New CheckBoxList
                                chkpregunta.ID = Convert.ToInt16(sdr02(0)) + Convert.ToInt16(n)
                                chkpregunta.Items.Add(Trim(sdr02(2)) + "**")
                                Panel3.Controls.Add(chkpregunta)
    
                            Loop
    
    
    
                        Catch ex As Exception
    
                            End Try
                            '*****************************************************
                            'fin opciones de pregunta para cada competencia
                            '*****************************************************
                        Loop
    
    
    
    
    
    
    
                Catch ex As Exception
    
                    End Try
                    Panel3.Controls.Add(New LiteralControl("<br />"))
    
                Next
    
                'Fin consulta captura descripción competencia
    
                Panel3.Controls.Add(New LiteralControl("<br />"))
                Panel3.Controls.Add(New LiteralControl("<br />"))
                Dim cmdGrabarExC As New Button
                cmdGrabarExC.PostBackUrl = "~/ViewTemplateExC.aspx"
                cmdGrabarExC.ID = "cmdgrabarexc"
                cmdGrabarExC.CssClass = "CommandButton"
                cmdGrabarExC.ValidationGroup = "chkPreguntas"
                cmdGrabarExC.Text = "Grabar plantilla"
                Panel3.Controls.Add(cmdGrabarExC)
    
    
    
    
    
        End Sub
    

    The par of code in Bold is the one I need to validate to ensure at least one option for each group is selected.

    example:

    option selected one

    checkbox option selected one + description

    checkbox option selected two + description

    checkbox option selected three + description

    checkbox option selected four + description

    Option selected Two

    checkbox option selected one + description

    checkbox option selected two + description

    checkbox option selected three + description

    Option selected three

    checkbox option selected one + description

    checkbox option selected two + description

    checkbox option selected three + description

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

    Please, let me know if this explanation is clear enough

    thanks for your time

    Tuesday, August 28, 2018 8:10 AM
  • User-1171043462 posted

    I don't know the exactly number of checkboxes as the user choose previously the options, so the number of checkboxes to validate is always variable.

    For CheckBoxList also you don't need to know. It can populate any no of CheckBoxes.

    Also my Validation program will validate any number of CheckBoxes.

    Tuesday, August 28, 2018 8:41 AM
  • User1877874361 posted

    In this sense, how can I call my ID field to validate from your script?

        <script type="text/javascript">
        function ValidateCheckBoxList(sender, args) {
            var checkBoxList = document.getElementById("<%=chkpregunta.id %>");
            var checkboxes = checkBoxList.getElementsByTagName("input");
            var isValid = false;
            for (var i = 0; i < checkboxes.length; i++) {
                if (checkboxes[i].checked) {
                    isValid = true;
                    break;
                }
            }
            args.IsValid = isValid;
        }
    </script>
    
    
    </head>
    <body>
    following your code I'llcreate  dynamically a CustomValidator for each group ...
     Dim n As Integer = 0
                                Do While sdr02.Read
                                    n = n + 1
                                    '1º.- creamos objeto checkbox
                                    ' Panel3.Controls.Add(New LiteralControl("&nbsp;&nbsp;"))
                                    Dim chkpregunta As New CheckBoxList
                                chkpregunta.ID = Convert.ToInt16(sdr02(0)) + Convert.ToInt16(n)
                                chkpregunta.Items.Add(Trim(sdr02(2)) + "**")
                                Panel3.Controls.Add(chkpregunta)
    
                            Loop
    
                            Dim chkvalidator As New CustomValidator
                            chkvalidator.ID = Convert.ToInt16(n)
                            chkvalidator.ErrorMessage = "Al menos una opción"
                            chkvalidator.ClientValidationFunction = "ValidateCheckBoxList"
    can I replace directly  chkfruits.clientID with chkpregunta.ID, or no???
    thanks!!
    Tuesday, August 28, 2018 9:21 AM
  • User475983607 posted

    Use a class selector on the checkbox container.

    Still unclear why you can't use standard data bound controls as it looks like you are just looping over a collection to create the checkboxes. 

    Tuesday, August 28, 2018 10:21 AM
  • User-1171043462 posted

    Why you need to create a Dynamic Validator and dynamic CheckBoxList?

    Just pass data from database to CheckBoxList and it will generate CheckBoxes

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, August 28, 2018 10:30 AM
  • User475983607 posted

    I agree with mudassarkhan.  It seems like you are making the design more complicated than needed.

    Tuesday, August 28, 2018 10:34 AM
  • User1877874361 posted

    I need to create dynamic checkboxes because not all records had the same information, if recordset returns a different number of records each time I cannot generate a static number of checkboxes.

    in first webform, user can select a no spscific number of categories from a Listbox Object. In current webform, for each category, data source read the options availables for each category.

    in example, first user can select two categories , but next user can select five or more. In each case the system will create a template for each group of categories selected so you will see available options in a checkbox list for each one.

    Tuesday, August 28, 2018 11:03 AM
  • User475983607 posted

    I don't get it.  The code shown is looping over a collection and creating server controls manually.  Rather than manually rendering server controls, simply assign the data source to the data bound control. 

    Users are isolated from one another in web applications.  Can you explain why the number of users and each user selection can affect the other users and how this dictates that the controls must be created manually?  It just does not make sense.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, August 28, 2018 11:19 AM
  • User1877874361 posted

    I am going to think about your words, this is the consequence of my own inexperience and then you are both right.

    I am making a longer and more complex waywhen in reality it could be simpler.

    Thank you very much for your support and cordial greetings

    Tuesday, August 28, 2018 11:31 AM
  • User-1171043462 posted

    Just one thing from my experience. Simpler applications are easier to maintain, find bugs and also change in future.

    Tuesday, August 28, 2018 11:34 AM
  • User1877874361 posted

    ok, thanks both for your time

    ;)

    Tuesday, August 28, 2018 11:44 AM