Question : CheckedChanged event fires when column is hidden

Hi Experts,

my ASP.net Gridview has several template columns with a single checkbox. Normally these checkboxes have an OnCheckedChanged event handler that writes the data back to the database, when the users clicks a checkbox. This works fine.

I would now like to make these columns invisible when not needed, so I added another checkbox to the page chkHideColumns. Initially, the columns are visible and everything is fine, even when the page is reloaded.

When I select the chkHideColumns checkbox, the columns are hidden nicely, but when the page is reloaded the next time (with the columns still hidden), the CheckedChanged events get fired fore every checkbox that is checked (as the value is retrieved from the database).

How can I stop this from happening, i.e. avoid that the CheckedChanged events are fired during the loading of the page - in other words, the CheckedChanged events should only fire when the users clicks them.

Thanks a lot for your support,
Thomas
Code Snippet:
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
  Dim i As Integer

  For i = 1 To 7 '7 columns with checkboxes
    GridView1.Columns(i + 1).Visible = not chkHideColumns.Checked
  Next
End Sub

Protected Sub chkA_CheckedChanged(ByVal sender As Object, ByVal e As System.EventArgs)
  Dim chk As CheckBox = sender
  ActionWhenCheckboxWasClicked(GridView1.DataKeys(chk.Attributes("Row")).Value, chk.Checked)
End Sub

Answer : CheckedChanged event fires when column is hidden

Strange, I was able to reproduce the problem, and I know something that may just fix your problem, but I don't really understand why these events are firing.  It really seems like a bug in asp.net from my experience.

Anyway, to the fix.

Instead of in Page_Load iterating through the columns and setting visibility, move that code to the CheckChanged of the appropriate checkbox.

Then after the loop finishes, rebind the gridview.

e.g.

        For i = 1 To 7
            GridView1.Columns(i + 1).Visible = chkFaecherAnzeigen.Checked
        Next
        GridView1.DataBind()

The rebinding "deletes" these check changed events.


Random Solutions  
 
programming4us programming4us