« Talk about good design | Main | CRM Call Outs »

May 15, 2006

Updated Rows in a GridView

My blog has moved. Please go to: http://jstawski.com/archive/2006/05/15/Updated-Rows-in-a-GridView.aspx

Have you ever wondered how to show the updated rows of a grid view? Well, I did, and I had to implement it for a client. Here's the basic idea. We need some kind of collection that holds the index of all the rows that had been modified. We need to persist the collection through every postback and then iterate through all the members of the collection and change the background color of the rows with the index specified in the collection.

All you need is to set up a gridview in your aspx page and have the folowing code (this time the code is vb)

variable:
'This is our collection of integers that will hold the updated rows
Dim rowindeces As New List(Of Integer)

'We need to persist the collection in the viewstate
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
  If Page.IsPostBack Then
    rowindeces = ViewState("rowindeces")
   End If
End Sub

'Whenever a row is updated, we add the row index into the collection (we don't care about duplicates)
Protected Sub GridView1_RowUpdating(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewUpdateEventArgs) Handles GridView1.RowUpdating
  rowindeces.Add(e.RowIndex)
End Sub

'Before we render the GridView, we need to paint the background of all the update rows
'in a different color by iterating through the collection
Protected Sub GridView1_PreRender(ByVal sender As Object, ByVal e As System.EventArgs) Handles GridView1.PreRender
  If rowindeces.Count > 0 Then
    For Each index As Integer In rowindeces
      GridView1.Rows(index).BackColor = Drawing.Color.Aqua
    Next
  End If
End Sub

'Last, but not least we save the collection in the viewstate
Protected Sub Page_PreRender(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.PreRender
  ViewState("rowindeces") = rowindeces
End Sub

Please note this code works only for GridViews that do not allow paging nor sorting. If you need to allow paging, then you must specify in the collection of indeces the page of the index. Something like this: 210 means page 2, index 10. When you iterate through the collection you need to substract 100*(page number) from each member of the collection and only deal with the member that range from 0 - 99 (this only works for paging with 100 members per page.) If sorting is allowed, then whenever the gridview is sorted, the indeces are out of order. You could clear the list of updated rows.

Happy Programming!

02:10 PM | Permalink

Comments

The comments to this entry are closed.