Geeks With Blogs

@dbutscher
  • dbutscher *sighs* One of the disadvantages of coordinating #c4c2011: You don't order enough Five Guys, you don't get no Five Guys :( about 1284 days ago
  • dbutscher Starbucks, we ask that you caffeinate and fuel our teams for one more day of this fabulous geekend. #c4c2011 about 1284 days ago
  • dbutscher Dale Carnegie, of "How to win friends and influence people", is buried in Belton Cemetery. #c4c2011 is building a site for them this wknd about 1285 days ago
  • dbutscher Special shout out to Premier Tech for rockin d'Bronx pizza for lunch! Thank you! #c4c2011 about 1285 days ago
  • dbutscher Day 2 of #c4c2011 starting up... I already smell code cooking! Yum! about 1285 days ago
  • dbutscher #c4c2011 is wrapping up for the night. Can't say enough thanks to everyone who's participating. See you tomorrow! about 1286 days ago

News
Add to Technorati Favorites
Doug Butscher Nothin' but .NET!

The subject of this blog should say it all. I've searched everywhere for a solution to this, to no avail. Essentially, what I wanted to do is this:
I needed to present a paged, filtered DataGrid to a user, with checkboxes added programmatically, and maintain the state of the checkboxes as PostBacks occurred.

There were tons of articles on how to programmatically add a checkbox to a DataGrid, which I had already figured out how to do. One way to do this (very inefficiently) is:

Stash the DataSet, DataView and DataGrid on the Session so it can be pulled after PostBacks. Then, iterate thru the DataGrid, then nest thru the DataSet, and set a Boolean value on the DataSet to match the value of the checkbox. So, you're looping thru the grid grid.Items.Count times, and for every item in the grid, you're looping thru the DataSet ds.Tables(”Table”).Rows.Count times. And that's just to capture the checkboxes.

As the user returns to that page of the grid, you'll need to pull the DataView off the Session, evaluate a column in the DataView against a column in the e.Items collection (from the DataGridItemEventArgs in the ItemCreated() event handler), and “check“ the box accordingly. Again, this is nested looping at it's worst.

This worked, but as I paged through, or as I changed the RowFilter on the dataview, the performance was horrible. I'm not know for writing efficient code, but this was ridiculous.

Make 'em sick, make 'em well.

So, after I filled my DataSet, I loaded my unique compare column (from the DataSet) along with a True/False value into a Collection. Since the Collection.Items() collection is read-only, I had to create a basic Class that exposed a property “CheckState“ to return True or False. That way, when I wanted to modify the value of the item in the collection for the given key, I could just modify a reference to the CheckState object. There will be code snippets below, btw.

So by now on PageLoad, I've got a filled DataSet, and a Collection representing key information. I stash that onto the Session, and I wait for a PostBack. When I get the PostBack, I loop thru the DataGrid, check the state of the checkboxes, and updating the collection accordingly. Again, stashing it back to the Session when I'm done.

When the page or RowFilter changes, I need to re-check checkboxes as necessary. I plugged into the ItemCreated event handler, and used the e.Items collection to fetch my key value, and I compared it to the Item in the Collection. If True, check the box.

Below is the code that I used to do all this (variable and table names have been changed to protect their anonymity).

Reply to this blog or email me if you wanna talk about it.

Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    Dim lcv As Integer
    Dim cb As CheckBox
    Dim ds As DataSet
    Dim oState As CheckState
    If IsPostBack Then
        ' pull the collection off the Session
        m_Collection = Session("Collection")
        For lcv = 0 To dg.Items.Count - 1
            ' get a checkbox object from the datagrid to evaluate
            cb = dg.Items(lcv).Cells(0).Controls(0)
            ' get the StateCheck object reference from the collection 
            ' that matches the key column from the datagrid
            oState = m_Collection.Item(dg.Items(lcv).Cells(1).Text)
            ' update the referenced object (which should update the collection)
            If cb.Checked Then
                oState.State = True
            Else
                oState.State = False
            End If
            ' now that we've updated, push the collection back to Session
            Session("Collection") = m_Collection
        Next
        Exit Sub
    End If
    PopulateGrid()
End Sub

Private Sub PopulateGrid()
    Dim oDR As
SqlDataReader
    Dim parmPostNum As
SqlParameter
    Dim parm As
SqlParameter
    Dim tableNames(0) As
String
    Dim iCompanyID As
Int32
    Dim dvPostMembers As
DataView
    Dim lcv As
Integer
    Dim lcv2 As
Integer
    Dim cb As
CheckBox
    Dim iCardNumber As
Integer
    Dim oState As Integer
    ...
    ' Fill the DataSet here
    ...

    m_Collection = New Collection

    ' set all to False, and add to the collection

    For lcv = 0 To ds.Tables("Table").Rows.Count - 1
        ds.Tables("Table").Rows(lcv).Item("CheckBoxChecked") =
False
        oState = New
CheckState
        oState.State =
False
        m_Collection.Add(oState, ds.Tables("Table").Rows(lcv).Item("KeyValue"))
    Next

    Session("Collection") = m_Collection
    dv = New DataView(ds.Tables("Table"))
    dv.RowFilter = "Column='filter'"
    Session("DataView") = dv
    Session("DataSet") = ds
    dg.DataSource = dv

    dg.DataBind()

End Sub

Private Sub dg_ItemCreated(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.DataGridItemEventArgs) Handles dg.ItemCreated
    If (e.Item.ItemType = ListItemType.Item) Or (e.Item.ItemType = ListItemType.AlternatingItem)
Then
        AddCheckbox(e)
    End
If
End Sub

Private Sub AddCheckbox(ByVal e As DataGridItemEventArgs)
    Dim cb As New
CheckBox
    Dim dv As
DataView
    
Dim keyval As
String
    Dim oState As
CheckState

   
dv = Session("DataView")
    keyval = dv.Item(e.Item.ItemIndex).Row.Item(13)
   
' pull the collection off the Session
    m_Collection = Session("Collection")

    ' get the CheckState of the current item in the data view
    oState = m_Collection.Item(keyval)
    cb.Checked = oState.State
    cb.EnableViewState =
True
    cb.ID = "chkItemChecked"
    cb.AutoPostBack =
False
    cell.HorizontalAlign = HorizontalAlign.Right
    cell.Controls.Add(cb)
End Sub

Public Class CheckState
    Private m_bCheckState As
Boolean
    Public Property State() As
Boolean
    Get
        Return
m_bCheckState
    End Get

    Set(ByVal Value As Boolean)
        m_bCheckState = Value
    End Set

    End Property
End
Class

Posted on Thursday, June 30, 2005 2:25 PM | Back to top


Comments on this post: Maintaining checkbox "checked" state in ASP.NET DataGrid

# re: Maintaining checkbox "checked" state in ASP.NET DataGrid
Requesting Gravatar...
A) use the viewstate instead of session... whats the point of 1000 users * N datagridrows stashed into 20 minute memory?

B) why not just stash a Hashtable into viewstate?

this would be the code to get a true/false (if defined for that checkbox name)
if(hash.Contains(checkBoxKey) && (int)hash[checkBoxKey]==true)
//um set the checkboxstate to true... :)

Left by Eric Newton on Jun 30, 2005 5:43 PM

# re: Maintaining checkbox "checked" state in ASP.NET DataGrid
Requesting Gravatar...
Thanks, Eric.
Since I have your ear... :P
Should ViewState also be used for the DataView for the DataGrid? My newbian paradigm has me filling my dataset, creating a dataview from it, setting a RowFilter, then stashing the DataView somewhere for retrieval on PostBack. If I can have upwards of several hundred records in a dataview, wouldn't that be too large for viewstate to quickly rehydrate?
I agree that replacing my collection with a hashtable and using viewstate insetad of session is much faster, efficient, and server-friendly. I will implement that July 5, assuming my fingers aren't too burnt to type.
Regarding dataviews and postbacks, is there a more effecient way to manage that object?

thanks again!

doug
Left by Doug Butscher on Jun 30, 2005 9:42 PM

# re: Maintaining checkbox "checked" state in ASP.NET DataGrid
Requesting Gravatar...
Hi Doug,
I just dealt with myself. I had cached DataSet which I wanted to use to build a grid dynamically each time the user selected from a dropdownlist, which corresponded to each table in the DataSet. I created a CheckBoxColumn which derived from ITemplate and added a custom event that was fired from the CheckBox's "CheckedChanged" event which is built in. Within this event, I'd query the checkbox's NamingContainer, which is the DataGridItem containing the checkbox. So now I've got my row reference. I created a custom DataGridCoordinateEventArgs class that holds the ColumnName and DataGridItem.ItemIndex I had just extracted and this gets passed as the event args into my custom event that is fired from the CheckedChanged event. This in turn gets captured on the PostBack to the form where I can extract the DataGridCoordinateEventArgs ColumnName and ItemIndex and perform some action on it in the wired up eventhandler. I was even able to do this in a completely dynamic datagrid...the only caveat is the AutoPostBack attribute should be true for the checkboxes in the column. If there isn't a lot of processing during rendering, this is minor. Best part, it is entirely event driven and sounds really cool :)
Hope this helps.
Left by Mike Nichols on Aug 02, 2005 3:05 PM

# re: Maintaining checkbox "checked" state in ASP.NET DataGrid
Requesting Gravatar...
Hi,

I've just started investigating trying to do the same thing you discuss above, but it's still a little out of my league. Have you updated your code since the original post, and would you mind posting all the code needed to make it work? I tried working with what is above, but I'm obviously missing something.

Thanks!
Left by KP on Aug 04, 2005 1:14 PM

# re: Maintaining checkbox "checked" state in ASP.NET DataGrid
Requesting Gravatar...
Hi,
Thanks a lot for u r code,but it was showing errors.could u plz share me the complete code for me.my email address is srinivas.n27@rediffmail.com


Thanks&Regards
sri
Left by SRI on Oct 14, 2005 1:38 AM

# re: Maintaining checkbox "checked" state in ASP.NET DataGrid
Requesting Gravatar...
ive been reading your conversations too. could u plz share me the complete code too.my email address is dktmoon@yahoo.com

thanks alot!!!
DKT
Left by DKT on Oct 21, 2005 8:36 PM

# re: Maintaining checkbox "checked" state in ASP.NET DataGrid
Requesting Gravatar...
I have scrapped this code, and I am in the process of re-writing everything (regarding the DataGrid functionality). Once *I* get it working, I will be sure to share with everyone else.

- Doug
Left by Doug Butscher on Nov 22, 2005 12:52 PM

# re: Maintaining checkbox "checked" state in ASP.NET DataGrid
Requesting Gravatar...
I want to know when to assing the .checked value to the chechbox on the page.
Left by Anand on Jun 21, 2007 11:53 AM

# re: Maintaining checkbox "checked" state in ASP.NET DataGrid
Requesting Gravatar...

I went through this scenario and you are right Doug this was a painful lesson. To make things worse I am using a dataset to bind my gridview and had to implement custom paging and sorting, however after many frustrating days and inventing new cusswords I made it work :) .I thought about doing it through the dataset but it would have been horrible performance wise. I just figured out how to make this work using a combination of client side and server side code. If someone wants I can send them an example code of how to do this.
Left by Farhan on Feb 06, 2008 4:35 PM

# re: Maintaining checkbox "checked" state in ASP.NET DataGrid
Requesting Gravatar...
wanted to know about coding in C#
Left by Rachna on Feb 16, 2008 1:23 AM

# re: Maintaining checkbox "checked" state in ASP.NET DataGrid
Requesting Gravatar...
tryryghgfh
k;l;kl
';l'l;'
ghjgjhgj
utgtfhfg
Left by hhg on Apr 16, 2008 4:59 AM

# re: Maintaining checkbox "checked" state in ASP.NET DataGrid
Requesting Gravatar...
When I see code like this, I just shake my head in disbelief that the coder does not see how inefficient they are.

if cb.Checked Then
oState.State = True
Else
oState.State = False
End If

when the equivalent is so OBVIOUS!

oState.State = cb.Checked
Left by no one on Oct 24, 2008 12:41 PM

# re: Maintaining checkbox "checked" state in ASP.NET DataGrid
Requesting Gravatar...
Watch out! Blog sniper! Thanks for the comment, but I was trying to illustrate something else.
Left by Doug on Oct 24, 2008 1:18 PM

# re: Maintaining checkbox "checked" state in ASP.NET DataGrid
Requesting Gravatar...
It goes on to clarify that it means virtue because this is concerned with emotions and actions and the meaning in these is praised and constitutes success. The majority have almost no doubt that such material could be of a some interest. Needless to be modest if someone lays open to public academic paper examples that are skilled and talented at the same time.
Left by Esteto on Jan 24, 2013 4:21 AM

Your comment:
 (will show your gravatar)
 


Copyright © Doug Butscher | Powered by: GeeksWithBlogs.net | Join free