Link to home
Start Free TrialLog in
Avatar of dbedoo
dbedoo

asked on

Checkboxes not reintializing

Hi Experts,
   I have an ASP.NET app that I am building for user security in my current intranet.  The problem Im having is I have a panel that dynamical grabs a list which I represent with a list of checkboxes.  It populates the value of the checkboxes checked or unchecked correctly.  The problem is when change some check value hit submit, I noticed that the db was not updated correctly and when the page came back I still had all of the "modified" changes on the page.  This is odd as I requery and rebuild the textboxes upon and update.  So in a nutshell I make changes hit post it is supposed to update the db and after updating it call the methods that rebuild the control and check or uncheck accordingly, but its not working.  I have stepped through the code and I watch it setting up the controls correctly but renders the old page??  

Here is a snippet to give you an idea :

Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        If IsPostBack Then
            doProcedures()
        Else
            pnSecurity.Style.Add("display", "none")
            indyDiv.Style.Add("display", "none")
        End If
    End Sub

    Private Sub doProcedures()
        Dim rv As New CRIdal.retVal
        Dim btn As String
        Dim employeeID As String = rv.returnedVal(Request, "lbEmployees")
        Dim empInfo As String()
        Dim security As String()
        Dim grpPolicy As String = rv.returnedVal(Request, "grpPolicy")
        Dim scView As Boolean

        btn = rv.whatButton(Request)
        Call intialize()

        Select Case btn
            Case "btnSaveSecurity"
                'Dim userid As Integer = rv.returnedVal(Request, CInt(txtUserID.Text))
                Call getItemizedSecuritySelected()
                Call loadUserInfo()
                Me.Controls.Add(New LiteralControl("<script>indyDivDisplay('indyDiv', 'pnSecurity', 1);openSCSecDiv('cbSCView', 'pnSecurityBreakout')</script>"))
          end select
         End sub

    Private Function getItemizedSecurity(ByVal userID As String) As String()
        Dim sqlState, errText As String
        Dim reader As SqlDataReader
        Dim sqlConn As New SqlConnection
        Dim qdb As New CRIdal.queryDBase
        Dim itemizedSecurity As String()

        sqlState = "SELECT readOnly, scView, fiscalView, irTracking, scAll, officeAll, programsAll FROM mydb WHERE userID = " & userID

        Try
            If qdb.queryDbase(sqlState, sqlConn, reader, False, errText, ) Then
                If reader.Read Then
                    ReDim Preserve itemizedSecurity(6)
                    itemizedSecurity(0) = reader.GetBoolean(0) 'ReadOnly
                    itemizedSecurity(1) = reader.GetBoolean(1) 'scView
                    itemizedSecurity(2) = reader.GetBoolean(2) 'fiscalView
                    itemizedSecurity(3) = reader.GetBoolean(3) 'IRTracking
                    itemizedSecurity(4) = reader.GetBoolean(4) 'scALL
                    itemizedSecurity(5) = reader.GetBoolean(5) 'officeALL
                    itemizedSecurity(6) = reader.GetBoolean(6) 'programsAll
                    qdb.closeConnections(reader, sqlConn)
                    Return itemizedSecurity
                Else
                    qdb.closeConnections(reader, sqlConn)
                End If
                Return Nothing
            Else
                qdb.closeConnections(reader, sqlConn)
            End If
        Catch ex As Exception
            qdb.closeConnections(reader, sqlConn)
        End Try
    End Function

    Private Sub loadUserInfo()
        Dim btn As String
        Dim employeeID As String
        Dim empInfo As String()
        Dim security As String()
        Dim grpPolicy As String
        Dim scView As Boolean
        Dim rv As New CRIdal.retVal

        employeeID = rv.returnedVal(Request, "lbEmployees")
        Call getEmployeeInfo(employeeID, empInfo)
        If Not empInfo Is Nothing Then
            Call loadControls(empInfo, scView)
            security = getItemizedSecurity(empInfo(0)) 'Call procedure if individual security.
            Call loadSCItemizedPanels(security)
        Else
            lblErrMessage.Text = "Employee found but is not registered.  Please register employee and try again."
        End If
    End Sub
    Private Sub loadSCSelection(Optional ByVal checkExisting As Boolean = False)
        Dim sqlState, errText As String
        Dim reader As SqlDataReader
        Dim sqlConn As New SqlConnection
        Dim qdb As New CRIdal.queryDBase
        Dim i, j As Integer
        Dim holdArray As String
        Dim allCheck, allEditCheck As Boolean
        Dim chkBox As CheckBox
        Dim chkBox2 As CheckBox
        Dim sc As String(,)

        sqlState = "SELECT coordinator_last + ', ' + coordinator_first, coordinator_id FROM mydb WHERE status = 'active' order by coordinator_last"
        Try
            If qdb.queryDbase(sqlState, sqlConn, reader, False, errText, ) Then
                If reader.HasRows Then
                    With pnSCSelection.Controls
                        .Add(New LiteralControl("<br><br>Service Coordinator Caseload<br><br>"))
                        .Add(New LiteralControl("<table border=1 width=90%><tr><td align=center>Edit</td>" & _
                                                                    "<td align=center>Read</td>" & _
                                                                    "<td align=center>SC Name</td></tr>"))
                    End With
                    'check here for all if checkExisting if yes set edit all flag
                    '////////////////////////////////////////////////////////////
                    'chkBox2.Attributes.Add("onclick", "selectAll('" & chkBox2.ID & "', " & holdArray & ")")
                    While reader.Read
                        ReDim Preserve sc(1, j)
                        sc(0, j) = reader.GetString(0)  'SCName
                        sc(1, j) = reader.GetInt32(1)    'SCID
                        If holdArray = "" Then holdArray = sc(1, j) _
                        Else holdArray += ", " & sc(1, j)
                        j += 1
                    End While
                    If allExists("editAll") Then
                        allEditCheck = True
                        chkBox2 = createCheckBoxControl("cbEdit", "", -1, -1, True, holdArray)
                    Else
                        chkBox2 = createCheckBoxControl("cbEdit", "", -1, -1, False, holdArray)
                    End If
                    '-->  
                    'check here for all if checkExisting if yes set all sc flag
                    '///////////////////////////////////////////////////////////
                    If allExists("scAll") Then
                        allCheck = True
                        chkBox = createCheckBoxControl("cbSC", "", -1, -1, True, holdArray)
                    Else
                        chkBox = createCheckBoxControl("cbSC", "", -1, -1, False, holdArray)
                    End If
                    With pnSCSelection.Controls
                        .Add(New LiteralControl("<tr><td align=center>"))
                        .Add(chkBox2)
                        .Add(New LiteralControl("</td><td align=center>"))
                        .Add(chkBox)
                        .Add(New LiteralControl("</td><td>&nbsp;&nbsp;"))
                        .Add(New LiteralControl("All SC"))
                        .Add(New LiteralControl("</td></tr>"))
                        '.Add(New LiteralControl("<br>"))
                        '-->
                    End With
                    Dim test As String = sc.GetUpperBound(1)
                    While i <= sc.GetUpperBound(1)
                        'check here for sc security here if checkExisting
                        '////////////////////////////////////////////////
                        Dim scName As String = sc(0, i)
                        Dim scid As Integer = sc(1, i)

                        ''check for edit
                        If Not allEditCheck Then
                            'Enters here if AllEditCheck=false
                            If secRowCheck("scSecFilter", scid, "scid", "editRights") Then
                                'Check if row exists for edit in scSecFilter
                                chkBox2 = createCheckBoxControl("cbEdit", "", scid, i, True)
                                chkBox = createCheckBoxControl("cbSC", "", scid, i, True)
                            Else
                                'Edit Flag doesnt exist or row doesnt exist check read flag
                                chkBox2 = createCheckBoxControl("cbEdit", "", scid, i)
                                If Not allCheck Then
                                    If secRowCheck("scSecFilter", scid, "scid", "readRights") Then
                                        chkBox = createCheckBoxControl("cbSC", "", scid, i, True)
                                    Else
                                        chkBox = createCheckBoxControl("cbSC", "", scid, i)
                                    End If
                                Else
                                    chkBox = createCheckBoxControl("cbSC", "", scid, i)
                                End If
                            End If
                        Else
                            chkBox2 = createCheckBoxControl("cbEdit", "", scid, i, True)
                            'If Not allCheck Then
                            '    If secRowCheck("scSecFilter", scid, "scid", "readRights") Then
                            '        chkBox = createCheckBoxControl("cbSC", "", scid, i, True)
                            '    Else
                            '        chkBox = createCheckBoxControl("cbSC", "", scid, i)
                            '    End If
                            'Else
                                chkBox = createCheckBoxControl("cbSC", "", scid, i, True)
                                'End If
                        End If
                        With pnSCSelection.Controls
                            .Add(New LiteralControl("<tr><td align=center>"))
                            .Add(chkBox2)
                            .Add(New LiteralControl("</td><td align=center>"))
                            .Add(chkBox)
                            .Add(New LiteralControl("</td><td>&nbsp;&nbsp;"))
                            .Add(New LiteralControl(scName))
                            .Add(New LiteralControl("</td></tr>"))
                            i += 1
                        End With
                    End While
                    qdb.closeConnections(reader, sqlConn)
                    pnSCSelection.Controls.Add(New LiteralControl("</table>"))
                Else
                    Response.Write("No Rows Returned:Line#827")
                    qdb.closeConnections(reader, sqlConn)
                End If
            Else
                Response.Write("No Similar Records: Null condition ln:831")
                qdb.closeConnections(reader, sqlConn)
            End If
        Catch ex As Exception
            qdb.closeConnections(reader, sqlConn)
        End Try
    End Sub


I left some functions out but point being ...  I step through the same code that is executed on load  after i udate the db but the same control values are returned   NOT the correct values from the DB?   Is there a way to implicitly dispose of the panels that contain the checkboxes ....

A work around would be to response redirect it but Id rather not because that will require passing around more "ids" and I want to avoid if possible.  Thanks in advance
Avatar of strickdd
strickdd
Flag of United States of America image

make sure you are not checking the checkboxes EVERY postback. Only populate them from the DB if not Page.IsPostback. The viewstate will maintain if they are checked or not. However you still need to create them each postback.
Avatar of Justin_W
Justin_W

1. Try disabling ViewState on the panel containing the Dynamic controls.

2. Make sure that you are assigning the ID property for all of the non-Literal Controls that you are dynamically creating and adding to the panel(s).

3. Are you using AJAX controls on this page?
Avatar of dbedoo

ASKER

It assisns a "check"  based on the db value...  I have verified that ..   I step through the code line by line after the update and it works correctly meaning it assigns .checked = true & .checked = false  where its supposed to but renders the previous state of the page.  And in case your wondering did verify the values saved in the db against what is returned after the post.

Right now I purposely broke the query so it does not update but enabled it to run the same procedure as if it did work to see if it would rerender the original state.  But no dice
Avatar of dbedoo

ASKER

Trying to disable viewstae now .....

Ids are ok ... I have verified

No Ajax
Avatar of dbedoo

ASKER

this is the event I use to build the chkboxes

    Private Function createCheckBoxControl(ByVal controlName As String, _
                                           ByVal label As String, _
                                           ByVal itemID As Integer, _
                                           ByVal index As Integer, _
                                           Optional ByVal checked As Boolean = False, _
                                           Optional ByVal array As String = Nothing) As CheckBox
        Dim chk As New CheckBox
        With chk
            .ID = controlName & itemID
            .Text = label
            If checked Then .Checked = True
            Select Case controlName
                Case "cbSC"
                    If Not array Is Nothing Then
                        .Attributes.Add("onclick", "selectAll('" & controlName & "', '" & array & "')")
                    End If
                Case "cbEdit"
                    If Not array Is Nothing Then
                        .Attributes.Add("onclick", "selectAll('" & controlName & "', '" & array & "');selectAll('cbSC', '" & array & "')")
                    End If
                Case Else
                      'do nothing
            End Select
        End With
        Return chk
    End Function
Avatar of dbedoo

ASKER

i added
.EnableViewState = False
to the code above

still not working
Avatar of dbedoo

ASKER

oops you said panel
my bad let me try that
Avatar of dbedoo

ASKER

tried EnableViewState = False on the panel still not working
Try Adding:
   .EnableViewState = False

for both the CheckBoxes and the panel(s) they're contained within.

If that doesn't work, try adding the CBs to a new panel (with a different ID) during each "refresh". You could do this by dynamically creating a new Panel with a unique ID each time you rebuild the list, and also calling Controls.Clear() on the container that you place these panels in before adding a new panel. That should ensure that only the new panel exists and may fix the issue if disabling the ViewState doesn't.
Also, try (temporarily) appending additional debug info to the "Text" property, so that you can verify whether the rebuilding of the CBs is affecting the display at all.
Avatar of dbedoo

ASKER

k i tried adding .EnableViewState = False to chkboxes and panels and I do a pnSCSelection.Controls.Clear() before goin into the literals section

still not working ....

trying to append debug text now...
Avatar of dbedoo

ASKER

ok I appended now() to the end of the .text  and after rerender it reflects that it is being re-created  

I know Im not crazy here I step through the code and I see it assigning .checked = true and the it renders without a check...  

I really appreciate your patience and suggestions
1. Just to be double-sure, append the Checked variable (t/f) to the text so that you can double-check the text against the checked state.

2. If possible, try creating a Subclass of the CheckBox class, and override (or shadow) the Checked property so that you can place a BreakPoint inside the Setter. Then use this subclass instead of the regular class in your code, and debug the process so that you can monitor all of the changes to the Checked property's state throughout the page lifecycle. That should definitively tell you whether it is a server-side or client-side issue.
Also, did you try using different IDs on each rebuild like I suggested above? That would result in different ClientIDs which should bypass any client-side issues if that were the cause.
Avatar of dbedoo

ASKER

Ok I appended the boolean check variable to the .text property and sure enough

there where trues next to the "unchecked"  check boxes so that is a start in the right direction...

As far as creating a subclass of the checkbox class  do you mean shadowing the .net checkbox class?  I would like to try this but Im not sure exactly how to do this (sounds like an excellent idea though)

the ids thing one problem is the ids map to the row ids in the db ...  should change the ids after the post?  or pre post.  
ASKER CERTIFIED SOLUTION
Avatar of Justin_W
Justin_W

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of dbedoo

ASKER

I changed the ids after the post by creating a hidden text box and setting it after post and then in the createcheckbox  function I append garbage on the end of the id if the hidden field was set and it worked like a charm....   Im a little confused though ....   How do I get around this ...   changing these ids will add cumbersome overhead ...  I will need a conditional parsing mechanism for every post... (flip flop routine)  i wanted to avoid that...  Is there any other way around it?
This leads me to suspect that the browser was at fault because the controls had the same ClientID throughout.

Solution:
Keep the hidden variable, but don't add garbage. Instead, start the variable at 0, and increment it as necessary, then append/include the value of the variable in the IDs. That way, you'll still be able to re-generate/derive the IDs at any time as long as you know the DB Record ID and the current increment value. It shouldn't add too much complexity to your page if you handle it right.
P.S. I think I actually ran into a similar problem with .NET CheckBoxes a few years ago, where sometimes they wouldn't re-render properly in certain very specific situations. I never did find a workaround other than to avoid it, so I wouldn't spend _too_ much time trying to find a "real" or "better" solution if I were you. Although, if you do, please post it. :)
Avatar of dbedoo

ASKER

Thanks for all of the advice, You were a great help.

I will also still try the shadow contruct too for future debugging.  I never thought of doing that....  You dont by chance have a link with an example of that do you?  

I wish I could offer more than 500 pts     It is well deserved.

Peace
You're welcome. I'm glad that I was able to help.

> You dont by chance have a link with an example of that do you?
Sorry, no. I've never seen any reference to that technique. I came up with it on my own.