GridView Column Sorting - Up/Down Arrows

December 7, 2008 14:32 by wjchristenson2

In this article, I will show you how to manually sort the GridView WebControl and display sort direction arrows.  The GridView has built-in sorting capabilities, however if we want visual feedback as to what column is being sorted and to what direction, we have to perform this ourselves.  While extending the GridView WebControl would be optimal, I'm going to show a quick way to get it done without creating a new GridView control.  Maybe in a future post I'll show how we can create a custom GridView control with sort arrows.  Here is a picture of what our final sorted GridView will look like.

Here is the HTML markup of our GridView:

<asp:GridView 
  ID="GridView1" 
  runat="server" 
  AutoGenerateColumns="False" 
  DataKeyNames="CustomerID" 
  CssClass="gridview" 
  RowStyle-CssClass="gridview_itm" 
  AlternatingRowStyle-CssClass="gridview_aitm" 
  HeaderStyle-CssClass="gridview_hdr" 
  PagerStyle-CssClass="gridview_pgr">
  <Columns>
    <asp:TemplateField>
      <HeaderTemplate>
        <asp:LinkButton ID="CustomerID_SortLnkBtn" runat="server" Text="Customer ID:" ToolTip="Click to Sort Column" CommandName="Sort" CommandArgument="CustomerID" CausesValidation="false" />
        <asp:ImageButton ID="CustomerID_SortImgBtn" runat="server" Visible="false" ToolTip="Click to Sort Column" CommandName="Sort" CommandArgument="CustomerID" CausesValidation="false" />
      </HeaderTemplate>
      <ItemTemplate><%#Eval("CustomerID")%></ItemTemplate>
    </asp:TemplateField>
                
    <asp:TemplateField>
      <HeaderTemplate>
        <asp:LinkButton ID="CompanyName_SortLnkBtn" runat="server" Text="Company Name:" ToolTip="Click to Sort Column" CommandName="Sort" CommandArgument="CompanyName" CausesValidation="false" />
        <asp:ImageButton ID="CompanyName_SortImgBtn" runat="server" Visible="false" ToolTip="Click to Sort Column" CommandName="Sort" CommandArgument="CompanyName" CausesValidation="false" />
      </HeaderTemplate>
      <ItemTemplate><%#Eval("CompanyName")%></ItemTemplate>
    </asp:TemplateField>
                
    <asp:TemplateField>
      <HeaderTemplate>
        <asp:LinkButton ID="ContactName_SortLnkBtn" runat="server" Text="Contact Name:" ToolTip="Click to Sort Column" CommandName="Sort" CommandArgument="ContactName" CausesValidation="false" />
        <asp:ImageButton ID="ContactName_SortImgBtn" runat="server" Visible="false" ToolTip="Click to Sort Column" CommandName="Sort" CommandArgument="ContactName" CausesValidation="false" />
      </HeaderTemplate>
      <ItemTemplate><%#Eval("ContactName")%></ItemTemplate>
    </asp:TemplateField>
  </Columns>
</asp:GridView>

The first step is to acquire customers from the Northwind database in the form of a DataTable.  We will then acquire a DataView object from our DataTable, and sort the view.  Once the data in our DataView has been sorted, we will then bind the GridView to the sorted DataView.  To accomplish the data retrieval, sorting, and data binding, I've created the following method:

Private Sub GridView1_DataBind()
    Dim dt As DataTable = New DataTable()

    'fill our datatable w/ customers from the DB
    Using conn As New SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings("NorthwindConnectionString").ConnectionString)
        Dim sql As String = "SELECT [CustomerID], [CompanyName], [ContactName] FROM [Customers] WITH (NOLOCK)"
        Dim cmd As SqlCommand = New SqlCommand(sql, conn)
        Dim reader As SqlDataReader = Nothing

        Try
            conn.Open()
            reader = cmd.ExecuteReader(CommandBehavior.CloseConnection)
            dt.Load(reader)
        Finally
            If Not reader Is Nothing AndAlso Not reader.IsClosed Then
                reader.Close()
            End If
        End Try
    End Using

    If dt.Rows.Count > 0 Then
        'get a dataView object from our dataTable of customers
        Dim dv As DataView = dt.DefaultView

        'if the user has elected to sort the gridview
        If Not String.IsNullOrEmpty(Me.SortBy("GridView1")) Then
            'get the sort expression and apply it to our dataView
            Dim sortExpr As String = Me.SortBy("GridView1") & " " & IIf(Me.SortDirection("GridView1") = WebControls.SortDirection.Ascending, "ASC", "DESC").ToString()
            dv.Sort = sortExpr
        End If

        'bind the dataView to our GridView
        Me.GridView1.DataSource = dv
        Me.GridView1.DataBind()
    End If
End Sub

The logic is pretty straight forward.  Take note to line 28.  I am using 2 properties to store what column I am sorting by and what direction it is being sorted.  I persist the values in the ViewState and I also pass what GridView I either want to retrieve or store values for.  This allows me to have more that 1 sorting GridView on my page at a time using the same 2 properties.  Here's the code for the 2 properties to assist us with sorting.

''' <summary>
''' Gets or sets the column name to be sorted.
''' </summary>
''' <param name="GridViewID">The unique ID of the GridView.</param>
''' <value></value>
''' <returns></returns>
''' <remarks></remarks>
Private Property SortBy(ByVal GridViewID As String) As String
    Get
        Dim o As Object = ViewState(GridViewID & "_SortBy")
        If Not o Is Nothing Then
            Return o.ToString()
        Else
            Return String.Empty
        End If
    End Get
    Set(ByVal value As String)
        ViewState(GridViewID & "_SortBy") = value
    End Set
End Property

''' <summary>
''' Gets or sets the sort direction.
''' </summary>
''' <param name="GridViewID">The unique ID of the GridView.</param>
''' <value></value>
''' <returns></returns>
''' <remarks></remarks>
Private Property SortDirection(ByVal GridViewID As String) As SortDirection
    Get
        Dim o As Object = ViewState(GridViewID & "_SortDirection")
        If Not o Is Nothing Then
            Return DirectCast(o, SortDirection)
        Else
            Return WebControls.SortDirection.Ascending
        End If
    End Get
    Set(ByVal value As SortDirection)
        ViewState(GridViewID & "_SortDirection") = value
    End Set
End Property

We have the sort by and sort direction properties (storing/persistance mechanisms).  We have the data retrieval, sorting of the data, and data binding method in place.  Now what we have to do is think about what events we need to account for.  First, on initial page load we'll want to fetch customer data and bind it to our GridView.  We'll only want to bind our GridView the first time the page loads and not subsequent postbacks.

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    If Not Page.IsPostBack Then
        'bind the gridview on page first load
        GridView1_DataBind()
    End If
End Sub

Now we are ready to make the magic happen.  We want to handle the GridView's RowDataBound event and either show or hide our up/down arrows if the user has elected to sort a column.

Private Sub GridView1_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GridView1.RowDataBound
    'if the row being dataBound is the header row - toggle sort image visibility/directions
    If e.Row.RowType = DataControlRowType.Header Then
        ToggleSortArrows(e.Row, "GridView1")
    End If
End Sub

Private Sub ToggleSortArrows(ByVal headerRow As GridViewRow, ByVal gridViewID As String)
    Dim sortImgBtn As ImageButton = Nothing

    'loop through each cell in the header row
    For Each tc As TableCell In headerRow.Cells
        'loop through each control in the cell
        For Each c As Control In tc.Controls
            'if the control is an image button and is our sort image button
            If TypeOf c Is ImageButton AndAlso c.ID.EndsWith("SortImgBtn") Then
                sortImgBtn = DirectCast(c, ImageButton)

                'if the image button is in the column being sorted
                If Me.SortBy(gridViewID) = sortImgBtn.ID.Split(CChar("_"))(0) Then
                    'show the image button and set its image url (sorted column)
                    sortImgBtn.Visible = True
                    If Me.SortDirection(gridViewID) = WebControls.SortDirection.Ascending Then
                        sortImgBtn.ImageUrl = "~/img/uparrow.gif"
                    Else
                        sortImgBtn.ImageUrl = "~/img/dnarrow.gif"
                    End If
                Else
                    'hide the image button (not a sorted column)
                    sortImgBtn.Visible = False
                End If
            End If
        Next
    Next
End Sub

Basically what we are doing is detecting if the row being DataBound is the header row or not.  If it is, we want to loop through each cell in the header row and get a handle on the column's associated sort image.  We use the ID of the sort image to acquire what column it represents and compare it to our SortBy property.  If it matches, then we want to show the appropriate sort direction image.  We hide the other sort images in non-sorted columns.

The only task we have left to account for is how to fire our sorting event.  Take a quick look at our GridView HTML markup.  The header row has both a LinkButton and ImageButton that raise a GridView command event to which we pass the column name that the user wants to sort by.  We then handle the event in our code behind.

Private Sub GridView1_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles GridView1.RowCommand
    If e.CommandName.ToUpper = "SORT" Then
        InitializeSort(e.CommandArgument, "GridView1")
        GridView1_DataBind()
    End If
End Sub

Private Sub InitializeSort(ByVal sortBy As String, ByVal gridViewID As String)
    If Me.SortBy(gridViewID) = sortBy Then
        If Me.SortDirection(gridViewID) = WebControls.SortDirection.Ascending Then
            Me.SortDirection(gridViewID) = WebControls.SortDirection.Descending
        Else
            Me.SortDirection(gridViewID) = WebControls.SortDirection.Ascending
        End If
    Else
        Me.SortBy(gridViewID) = sortBy
        Me.SortDirection(gridViewID) = WebControls.SortDirection.Ascending
    End If
End Sub

Once we capture our sort row command, we initialize our SortBy and SortDirection properties.  We either toggle the direction of the sorted column or the sorted column is a new column to be sorted to which we default the column to be sorted Ascending.

I hope this article helped a bit.  It's a quick way to get a GridView sorted with visual indicators (sort arrows) without creating a new custom GridView control.

GridViewSorting_Soln.zip (90.61 kb)

Bookmark and Share

Save Scroll Position GridView Control

October 29, 2008 11:09 by wjchristenson2

I've seen a lot of articles on the web describing how to scroll a GridView.  Some of those articles may even go a little deeper and show you how to persist the scroll position across PostBacks.  What I haven't been able to find is how to encapsulate the scrolling and saving/persisting of the scroll position into a custom GridView control.  That is what I am going to show you how to do today.

There are many ways a developer may want to scroll their GridView (horizontal, vertical, freezing the header/footer, etc).  I'm not going to go into creating a bullet proof GridView control to accomplish those tasks.  My objective is to show you a technique to save/set the scroll position across PostBacks within a custom GridView control.

Here is what our end GridView control will look like.  First you can see a scrollable GridView.  When we scroll the GridView and then click the PostBack button, the page will perform a PostBack and the <div> will scroll itself back to where we left off.



So let's get to it.  First thing we do is create a new control and inherit from the GridView.  We then implement the IPostBackDataHandler to get and set our scroll position across PostBacks.  You'll see the LoadPostData function accomplishes this.  Take note that in line 3 I am referencing the name of my hidden field that I'll go over later.  We also tell the page that our new custom GridView (Me) has data to PostBack and we can do this in the GridView's Init.

Public Function LoadPostData(ByVal postDataKey As String, ByVal postCollection As System.Collections.Specialized.NameValueCollection) As Boolean Implements System.Web.UI.IPostBackDataHandler.LoadPostData
    'get and set the new scroll position
    Dim postedValue As String = postCollection(Me.ClientID & "_scroll")
    If Not postedValue Is Nothing Then
        Dim presentValue As Integer = Me.ScrollPosition
        Me.ScrollPosition = CType(postedValue, Integer)
        Return Not presentValue.Equals(Me.ScrollPosition)
    End If
End Function

Public Sub RaisePostDataChangedEvent() Implements System.Web.UI.IPostBackDataHandler.RaisePostDataChangedEvent
    'do nothing
End Sub

Private Sub ScrollingGridView_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Init
    If Not Me.Page Is Nothing Then
        'indicates that the control has data to postback
        Me.Page.RegisterRequiresPostBack(Me)
    End If
End Sub

In order to scroll my new custom GridView, I need to wrap my GridView with a <div> tag.  To do this, I can override the Render method like so:

Protected Overrides Sub Render(ByVal writer As System.Web.UI.HtmlTextWriter)
    If Not Me.Page Is Nothing Then
        Me.Page.VerifyRenderingInServerForm(Me)
    End If

    Me.PrepareControlHierarchy()

    If Not Me.DesignMode Then
        If String.IsNullOrEmpty(Me.ClientID) Then
            Throw New HttpException("ScrollingGridView must be parented!")
        End If

        writer.AddAttribute(HtmlTextWriterAttribute.Id, String.Format("{0}_div", Me.ClientID), True)
        writer.AddAttribute("onScroll", "saveScrollPos('" & String.Format("{0}_scroll", ClientID) & "', '" & String.Format("{0}_div", Me.ClientID) & "');")
        writer.AddStyleAttribute(HtmlTextWriterStyle.OverflowY, "auto")
        writer.AddStyleAttribute(HtmlTextWriterStyle.Height, "300px")
        writer.RenderBeginTag(HtmlTextWriterTag.Div)
    End If

    Me.RenderContents(writer)

    If Not Me.DesignMode Then
        writer.RenderEndTag()
    End If
End Sub

Notice that when I render my <div> that I also wire in a call to my JavaScript function to save the scroll position "onScroll".  At this point I have completed the PostBack data handling and I have shown you how to wrap a <div> around our GridView so we can scroll and it will call a JavaScript function "onScroll" that will save the position to a hidden field.

The next phase is to emit our JavaScripts.  I always emit JavaScript in the PreRender phase of a control's lifecycle as the ClientID should be set at that point.  We need a function to set the scroll position and a function to save the scroll position.  Here they are:

'generate & register javascript blocks
Dim key As String = "ScrollingGridView"
Dim script As StringBuilder = New StringBuilder()
With script
    .AppendLine("function saveScrollPos(whereID, whatID) {")
    .AppendLine("  document.getElementById(whereID).value = document.getElementById(whatID).scrollTop;")
    .AppendLine("}")
    .AppendLine("function setScrollPos(whereID, whatID) {")
    .AppendLine("  document.getElementById(whatID).scrollTop = (document.getElementById(whereID).value.length > 0) ? document.getElementById(whereID).value : 0;")
    .AppendLine("}")
End With

If Not sm Is Nothing Then
    ScriptManager.RegisterStartupScript(Me.Page, Me.GetType(), key, script.ToString(), True)
Else
    Me.Page.ClientScript.RegisterStartupScript(Me.GetType(), key, script.ToString(), True)
End If

Notice we either acquire or save the scroll position to our hidden field.  Now how do we emit a hidden field inside our GridView?  My first attempts were to override the Render of the GridView control and emit hidden field there.  It didn't work.  I ended up registering the hidden field via .NET's scripting objects instead.  Check it out:

'register our hidden field to save our scroll position
If Not sm Is Nothing Then
    ScriptManager.RegisterHiddenField(Me.Page, String.Format("{0}_scroll", Me.ClientID), Me.ScrollPosition.ToString())
Else
    Me.Page.ClientScript.RegisterHiddenField(String.Format("{0}_scroll", Me.ClientID), Me.ScrollPosition.ToString())
End If

Notice that I assign the scroll position to the hidden field's value.  Last thing we need to do is register a startup script to get the persisted scroll position from our hidden field and scroll our <div>.  If you remember we created a JavaScript function for this (setScrollPosition).

'generate & register startup javascripts
key = String.Format("{0}_setScrollPos", Me.ClientID)
script = New StringBuilder()
script.AppendLine("setScrollPos('" & String.Format("{0}_scroll", Me.ClientID) & "','" & String.Format("{0}_div", Me.ClientID) & "');")
If Not sm Is Nothing Then
    ScriptManager.RegisterStartupScript(Me.Page, Me.GetType(), key, script.ToString(), True)
Else
    Me.Page.ClientScript.RegisterStartupScript(Me.GetType(), key, script.ToString(), True)
End If

Putting it all Together:

In summary, we persist the scroll position of the div that wraps our GridView via a hidden field which is registered via the Page.ClientScript or ScriptManager object.  We wrap the GridView with a <div> by overriding the GridView's Render method.  The <div> saves the scroll position to the hidden field as the <div> is scrolled.  We acquire the value stored in the hidden field via the LoadPostData function.  Once a PostBack occurs, we set the scroll position of the <div> with a startup script.


ScrollingGridView_Soln.zip (97.19 kb)
Bookmark and Share

MultiSelect GridView Control

September 17, 2008 09:18 by wjchristenson2

In this post, I am going to create an ASP .NET GridView that supports multiple selection.  This is a common feature that is desired by many web developers.  The new GridView control I will create will support the following: selection of 1 row at a time, toggling of all rows to be selected or deselected at once, coloring of what row(s) are selected, what column index we want our selection checkboxes to be put in, and a way to access what DataKeys are selected on PostBack.  Here is what our final control will look like.

The first step to creating our control is setting up our solution.  You can download the solution in its entirety below.  I have a project for my new control and a web project to test it in.  I am using the Northwind SQL database for my DataSource.  Now we are ready to start programming our MultiSelectGridView control.  We first setup our class-wide variables and properties.

<ToolboxData("<{0}:MultiSelectGridView runat=server></{0}:MultiSelectGridView>")> _
  Public Class MultiSelectGridView
    Inherits GridView

    Private _tfMultiSelect As TemplateField = Nothing

#Region "Public Properties"
    <DefaultValue(False), Category("MultiSelect"), Description("Indicates whether or not multiselection is enabled.")> _
    Public Property EnableMultiSelect() As Boolean
        Get
            If Not ViewState("EnableMultiSelect") Is Nothing Then
                Return DirectCast(ViewState("EnableMultiSelect"), Boolean)
            Else
                Return False
            End If
        End Get
        Set(ByVal value As Boolean)
            ViewState("EnableMultiSelect") = value
        End Set
    End Property

    <Bindable(True), Category("MultiSelect"), TypeConverter(GetType(WebColorConverter)), Description("Specifies the background color of a selected row.")> _
    Public Property MultiSelectColor() As Color
        Get
            If ViewState("MultiSelectColor") Is Nothing Then
                ViewState("MultiSelectColor") = System.Drawing.ColorTranslator.FromHtml("#FFCC99")
            End If
            Return DirectCast(ViewState("MultiSelectColor"), Color)
        End Get

        Set(ByVal value As Color)
            ViewState("MultiSelectColor") = value
        End Set
    End Property

    <Bindable(True), Category("MultiSelect"), Description("Specifies the where the multiselection column should be placed.")> _
    Public Property MultiSelectColumnIndex() As Integer
        Get
            If Not ViewState("MultiSelectColumnIndex") Is Nothing Then
                Return DirectCast(ViewState("MultiSelectColumnIndex"), Integer)
            Else
                Return -1
            End If
        End Get
        Set(ByVal value As Integer)
            ViewState("MultiSelectColumnIndex") = value
        End Set
    End Property

    Public ReadOnly Property SelectedDataKeys() As DataKeyArray
        Get
            Return GetSelectedDataKeys()
        End Get
    End Property
#End Region

We want to extend the GridView control so we first inherit from it.  I've defined 4 properties.  First is to toggle whether or not we want to enable multiselection or not.  The second is used to define what color we want to use to delineate the selected state of a row.  The third property is used to allow the developer to specify where they wish to put the multiple selection column.  The final property (SelectedDataKeys) is an array of selected DataKeys that can be accessed programmatically when a PostBack occurs.

A problem I had at first, was how to add columns in a GridView control.  At first, I tried to add them in the Init and the CreateChildControls and then work with them later on in the control lifecycle.  This *can* work, however you'll soon find out that if you try and access the Columns property, you may find that there are no other columns outside the one you added if you set AutoGenerateColumns = True.  For instance, if you are trying to do a GridView.Columns.Count, you may have more columns than what the property returns.  The Columns property only returns what columns are defined.  So if you are trying to programmatically insert columns or move them around, you may run into issues if you are trying to do that in the Init or PreRender or Load events of your control lifecycle.  The key to adding our column is to Override the CreateColumns function.  We want to let the GridView create its normal columns and then we want to insert our multiselect column wherever the column index tell us to.

    Protected Overrides Function CreateColumns(ByVal dataSource As System.Web.UI.WebControls.PagedDataSource, ByVal useDataSource As Boolean) As System.Collections.ICollection
        'let the GridView create the default set of columns
        Dim columnList As ICollection = MyBase.CreateColumns(dataSource, useDataSource)
        Dim extendedColumnList As ArrayList = New ArrayList(columnList)

        If Me.EnableMultiSelect Then
            'add our multi-select checkbox column
            _tfMultiSelect = New TemplateField()
            With _tfMultiSelect
                .HeaderTemplate = New MultiSelectColumnTemplate(DataControlRowType.Header)
                .ItemTemplate = New MultiSelectColumnTemplate(DataControlRowType.DataRow)
            End With

            If Me.MultiSelectColumnIndex < 0 Or Me.MultiSelectColumnIndex > extendedColumnList.Count Then
                extendedColumnList.Add(_tfMultiSelect)
            Else
                extendedColumnList.Insert(Me.MultiSelectColumnIndex, _tfMultiSelect)
            End If
        End If

        Return extendedColumnList
    End Function

Above is the overridden CreateColumns function.  We first see if multiselection is enabled.  If it is, we insert our multiselect column (template field) into the collection of GridView columns.  We do some logic here to ensure the column is inserted in the appropriate position.  This gets our multiselect column into the GridView, however now we need to wire in some Javascript.

    Private Sub MultiSelectGridView_PreRender(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.PreRender
        If Me.EnableMultiSelect Then
            'declare variables used to initialize onclick client scripts
            Dim cbxMultiSelect As CheckBox = Nothing
            Dim cbxSingleSelect As CheckBox = Nothing
            Dim hidCheckBoxIDs As HiddenField = Nothing
            Dim checkboxIDs As ArrayList = New ArrayList()
            Dim selectColor As String = System.Drawing.ColorTranslator.ToHtml(Me.MultiSelectColor)

            'set header checkbox onclick
            : If Me.ShowHeader And Not Me.HeaderRow Is Nothing Then
                cbxMultiSelect = CType(Me.HeaderRow.FindControl("cbxMultiSelect"), CheckBox)
                hidCheckBoxIDs = CType(Me.HeaderRow.FindControl("hidCheckBoxIDs"), HiddenField)
                cbxMultiSelect.Attributes.Add("onClick", "toggleCheckBox(this, '" & cbxMultiSelect.ClientID & "', '" & hidCheckBoxIDs.ClientID & "', '" & selectColor & "');")
            End If

            'set data row checkbox onclick
            For Each gvr As GridViewRow In Me.Rows
                cbxSingleSelect = CType(gvr.FindControl("cbxMultiSelect"), CheckBox)

                If cbxMultiSelect Is Nothing Or hidCheckBoxIDs Is Nothing Then
                    cbxSingleSelect.Attributes.Add("onClick", "toggleCheckBox(this, '', '', '" & selectColor & "');")
                Else
                    cbxSingleSelect.Attributes.Add("onClick", "toggleCheckBox(this, '" & cbxMultiSelect.ClientID & "', '" & hidCheckBoxIDs.ClientID & "', '" & selectColor & "');")
                End If

                If cbxSingleSelect.Checked Then
                    gvr.Style.Add("background-color", selectColor)
                Else
                    gvr.Style.Add("background-color", "")
                End If
                checkboxIDs.Add(cbxSingleSelect.ClientID)
            Next

            'set hidden field value w/ checkbox client ids
            If Not hidCheckBoxIDs Is Nothing Then
                hidCheckBoxIDs.Value = Join(checkboxIDs.ToArray(), ",")
            End If

            RegisterClientScriptBlock()
        End If
    End Sub

I wire in client-side script in the control's PreRender phase of its lifecycle.  Basically when a checkbox is clicked, I call a Javascipt function to do perform background color changes and toggle the check or uncheck of other checkboxes.  So if I check the toggle all checkbox, all rows will be selected.  If I uncheck the toggle all checkbox, all rows will be deselected.  If I select each row manually 1 at a time and all are checked, I check the "toggle all" checkbox with Javascript and vice versa.  Here's the Javascript code that performs this logic.

  var lastColorUsed;
  function toggleCheckBox(thisCheckBox, multiSelectID, checkBoxIDs, selectedColor) {
    var arrayIDs;
    if (checkBoxIDs.length > 0) 
      arrayIDs = document.getElementById(checkBoxIDs).value.split(',');
    var cbxMultiSelect = document.getElementById(multiSelectID);
    if (thisCheckBox == cbxMultiSelect) {
      var cbx;
      for (var i = 0; i < arrayIDs.length; i++) {
        cbx = document.getElementById(arrayIDs[i]);
        if (cbx) {
          if (!cbx.disabled) {
              cbx.checked = thisCheckBox.checked;
              if (cbx.checked) {
                cbx.parentNode.parentNode.parentNode.style.backgroundColor = selectedColor;
                lastColorUsed = selectedColor;
              } else {
                cbx.parentNode.parentNode.parentNode.style.backgroundColor = '';
                lastColorUsed = '';
              }
          }  
        }
      }
    } else {
      if (thisCheckBox.checked) {
        thisCheckBox.parentNode.parentNode.parentNode.style.backgroundColor = selectedColor;
        lastColorUsed = selectedColor;

        if (cbxMultiSelect) {
          var allChecked = true;
          for (var i = 0; i < arrayIDs.length; i++) {
            allChecked = document.getElementById(arrayIDs[i]).checked;
            if (!(allChecked))
              break;
          }
          if (allChecked) 
            cbxMultiSelect.checked = true;
        }
      } else {
        thisCheckBox.parentNode.parentNode.parentNode.style.backgroundColor = '';
        lastColorUsed = '';
        if (cbxMultiSelect) 
          cbxMultiSelect.checked = false;
      }
    }
  }

Now we need to acquire what rows are selected when the page performs a PostBack.  I've created a public property that returns an array of DataKeys that were selected.  The DataKeys can be 1 or a combination of values to uniquely identify the row.  Make sure you define what column(s) or object(s) of each row make up the DataKey by setting the DataKeyNames property of the GridView.  The SelectedDataKeys property calls our function below.

    Private Function GetSelectedDataKeys() As DataKeyArray
        Dim keys As ArrayList = New ArrayList()

        If Me.EnableMultiSelect Then
            Dim cbxMultiSelect As CheckBox = Nothing

            If Me.DataKeys.Count > 0 Then
                For Each gvr As GridViewRow In Me.Rows
                    cbxMultiSelect = CType(gvr.FindControl("cbxMultiSelect"), CheckBox)

                    If Not cbxMultiSelect Is Nothing AndAlso cbxMultiSelect.Checked Then
                        keys.Add(Me.DataKeys(gvr.RowIndex))
                    End If
                Next
            End If
        End If

        Return New DataKeyArray(keys)
    End Function

What we do here is loop through each row of the GridView and get a handle on the multiselect checkbox.  If it is checked, we get the associated DataKeys for the row and add it to our ArrayList.  We return all selected DataKeys when finished looping through all rows of the GridView.  Now we are ready to use our control.

<cc1:MultiSelectGridView 
  ID="MultiSelectGridView1" 
  runat="server" 
  DataSourceID="SqlDataSource1" 
  DataKeyNames="RegionID" 
  EnableMultiSelect="True" 
  MultiSelectColor="#9EC630" 
  MultiSelectColumnIndex="0" />

Here is a simple use of our MultiSelectGridView control.  Remember I am using the Northwind database via my SqlDataSource1.  What's important here is the MultiSelect properties.  I enable multiselection, set the selected color, and then place the multiselect column on the far left of my GridView.  After I've selected what rows I want, I click a button and display the SelectedDataKeys on my page.  Here is how I use the SelectedDataKeys property programmatically.

    Protected Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button1.Click
        Dim selectedKeys As StringBuilder = New StringBuilder()
        For Each key As DataKey In Me.MultiSelectGridView1.SelectedDataKeys
            selectedKeys.Append(", " & key(0).ToString())
        Next

        If selectedKeys.Length > 0 Then selectedKeys.Remove(0, 2)
        lblSelectedItems.Text = selectedKeys.ToString()
    End Sub

That's all there is to it.  You now have a GridView that allows you to multiselect rows!


GridViewMultiSelect_Soln.zip (111.25 kb)
Bookmark and Share

Bind a Collection to a GridView

August 8, 2008 05:41 by wjchristenson2

Over the past few months I've had some requests to show how you can bind a custom object collection to a GridView.  When looking deeper into the collections, I noticed that the developers were working way to hard to create their collection class.   The collections were inheriting from System.Collections.Specialized.NameObjectCollectionBase and implementing IEnumerator, IEnumerable, & IUpdatable, etc to accomplish some simple tasks (ie: add, remove, for each loops, etc).  When implementing these interfaces, the developers were manually having to wire everything in.  On top of this, they were having problems binding to .NET controls.  Another quick point to make here is that the specialized collection does type casting at run time.

What I proposed was to inherit from System.Collections.Generic.List instead.  What this does is allow them to do their basic add, remove, sort, and manipulate their lists.  It also is strongly typed and can be accessed by index.  Generics provide better type safety and performance than non-generic collections (ie NameObjectCollectionBase mentioned above).

I'm going to create a simple vehicle collection and bind a GridView to it using the Generic.List.

Public Class Vehicle
    Private _Make As String = String.Empty
    Private _Model As String = String.Empty

    Public Property Make() As String
        Get
            Return _Make
        End Get
        Set(ByVal value As String)
            _Make = value
        End Set
    End Property

    Public Property Model() As String
        Get
            Return _Model
        End Get
        Set(ByVal value As String)
            _Model = value
        End Set
    End Property

    Public Sub New()

    End Sub

    Public Sub New(ByVal make As String, ByVal model As String)
        _Make = make
        _Model = model
    End Sub
End Class

Here is the vehicle class (object) that we'll reference in our collection.  Now for the collection.

Imports System.Collections.Generic

Public Class Vehicles
    Inherits List(Of Vehicle)

#Region "Constructors"
    Public Sub New()
        MyBase.New()
    End Sub

    Public Sub New(ByVal capacity As Integer)
        MyBase.New(capacity)
    End Sub

    Public Sub New(ByVal collection As IEnumerable(Of Vehicle))
        MyBase.New(collection)
    End Sub
#End Region

End Class

You'll notice how we inherit from System.Collections.Generic.List and cast the collection as a type of Vehicle.  It's as simple as that.  I added 3 constructors for your own reference.  Now all we have to do is add some data to the collection and bind a GridView to it.

Imports CollectionDataBinding.BLL

Partial Public Class _Default
    Inherits System.Web.UI.Page

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        If Not Page.IsPostBack() Then
            GridView1_DataBind()
        End If
    End Sub

    Private Sub GridView1_DataBind()
        Dim myVehicles As Vehicles = New Vehicles()
        myVehicles.Add(New Vehicle("Ford", "Mustang"))
        myVehicles.Add(New Vehicle("Pontiac", "Grand AM"))

        Me.GridView1.DataSource = myVehicles
        Me.GridView1.DataBind()
    End Sub
End Class

On page load, I bind the GridView if it is not a postback.  I create a new instance of the Vehicles collection and add 2 vehicles to it.  I then simply set the data source of the GridView to the Vehicle collection and call DataBind().  Now, each public property will be mapped and shown in your GridView if you have AutoGenerateColumns="true" set.  If you don't do this, you'd approach the custom column mappings the same way as with a DataTable, DataView, etc (TemplateField, Eval expressions).

CollectionDataBinding_Soln.zip (89.23 kb)

>>>>> Edit 8/21/2008 <<<<<

I found another article that relates to this post.  It's a great reference as to the benefits of using generic collections.  The article lists the following reasons why you should use generic collections.

  1. Readability and simplicity of your code. Let’s take the case of getting the first string in a list of strings. With generics you would declare List<T> myList = new List<T>(); and then say string firstString = myList[0] just like working with arrays. This syntax is much more simple and readable than what you used to have to write which was ArrayList myList = new ArrayList(); and then string firstString = myList[0] as string;
  2. Performance. Every time you add a value type to a non-generic collection you have to box it to make it an object and every time you retrieve a value type from a non-generic collection you have to unbox it back from object. Even with reference type you still need to cast back to the correct type when retrieving items.
  3. Working against new smaller Framework SKUs. In Silverlight we decided to remove all the concrete non-generic collections completely from the codebase. This is mostly because the Silverlight core managed libraries is set to be the smallest useful set of classes. It’s also possible that other future small frameworks will not have the non-generic collections in store. If you ever plan to write code for those frameworks — you should convert it to use the generic collections.
  4. Better type-safe libraries. If you are developing libraries to be consumed by 3rd parties you should most definitely use generic collections when possible. This would allow consumer of your libraries to quickly figure out what’s expected to be stored in the collections instead of having to guess or figure out from documentation.
Bookmark and Share

Custom GridView Paging

August 7, 2008 02:00 by wjchristenson2

One of the first topics I searched for when working with the ASP.NET GridView control was how to page data with it.  I quickly discovered that the GridView control has built-in paging capabilities.  However, I wanted to customize my GridView pager.  The built-in pager just didn't cut it for me.  Not only did I want to customize the pager, I didn't want to have to define my pager template and wire everything in each time I used my GridView control because it would be used 100's of times.

In order to encapsulate the paging features I desire, I am going to make my own custom GridView control.  In my pager I want the following:
1) A "Page X of Y" caption
2) Basic first, previous, next, and last navigation
3) A page selector drop down list so the user can jump to a page quickly

If you've used the GridView before, you may have utilized the built-in paging modes.  I don't necessarily want to remove that functionality.  I want to add to it.  So what I am going to do is create a public property called "PagerType" where we can specify if we want to use the GridView's built-in paging or if we want to use our custom paging.

Public Class PagingGridView
    Inherits GridView

    Public Enum PagerTypes
        Regular = 0
        Custom = 1
    End Enum

    <DefaultValue(PagerTypes.Custom), Category("Paging"), Description("Indicates whether to use the built-in custom pager or not.")> _
    Public Property PagerType() As PagerTypes
        Get
            If Not ViewState("PagerType") Is Nothing Then
                Return DirectCast(ViewState("PagerType"), PagerTypes)
            Else
                Return PagerTypes.Custom
            End If
        End Get
        Set(ByVal value As PagerTypes)
            ViewState("PagerType") = value
        End Set
    End Property

From this code snippet we are inheriting from the GridView control, defining our 2 paging types (regular & custom), and we define our pager type property.  In order for our pager to be initialized, we need to override the InitializePager method.  What this method does is initialize the pager row when paging is enabled.  We need to determine if we want to allow the GridView to use its built-in pager or if we need to use our custom pager.  A simple select case statement will do the trick here.

    Protected Overrides Sub InitializePager(ByVal row As System.Web.UI.WebControls.GridViewRow, ByVal columnSpan As Integer, ByVal pagedDataSource As System.Web.UI.WebControls.PagedDataSource)
        Select Case Me.PagerType
            Case PagerTypes.Custom
                InitCustomPager(row, columnSpan, pagedDataSource)
            Case Else
                MyBase.InitializePager(row, columnSpan, pagedDataSource)
        End Select

You'll notice that we have an InitCustomPager method we call to initialize our pager controls.  I'm not going to post the code snippet for this.  You can download the code and sift through it if you want.  The things to note is the wiring of events.  Our first, previous, next, and last image buttons throw a Command event and the drop down list throws a SelectedIndexChanged event.  Our PagingGridView control will handle these events and fire a the OnPageIndexChanging event which can be handled by the page.

    Protected Sub ddlPages_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs)
        Dim newPageIndex As Integer = CType(sender, DropDownList).SelectedIndex
        OnPageIndexChanging(New GridViewPageEventArgs(newPageIndex))
    End Sub

    Protected Sub PagerCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.CommandEventArgs)
        Dim curPageIndex As Integer = Me.PageIndex
        Dim newPageIndex As Integer = 0

        Select Case e.CommandName
            Case "First"
                newPageIndex = 0
            Case "Previous"
                If curPageIndex > 0 Then
                    newPageIndex = curPageIndex - 1
                End If
            Case "Next"
                If Not curPageIndex = Me.PageCount Then
                    newPageIndex = curPageIndex + 1
                End If
            Case "Last"
                newPageIndex = Me.PageCount
        End Select

        OnPageIndexChanging(New GridViewPageEventArgs(newPageIndex))
    End Sub

Here are the even handlers for my image buttons and the page drop down list.  You'll see that in each handler, I raise the OnPageIndexChanging event passing in the new page index to navigate to.

So let's use our new PagingGridView control.  I'm going to dynamically create a DataTable object on the fly to bind my GridView to for this example.  I also created some css and images to make the GridView look good.  You can find them in the download package if you need them.

<cc1:PagingGridView ID="PagingGridView1" runat="server" 
  CssClass="paging_gridview" PageSize="5" AllowPaging="true" Width="400">
  <RowStyle CssClass="paging_gridview_itm" />
  <PagerStyle CssClass="paging_gridview_pgr" />
  <HeaderStyle CssClass="paging_gridview_hdr" />
  <AlternatingRowStyle CssClass="paging_gridview_aitm" />
</cc1:PagingGridView>

Here is the HTML markup for our new PagingGridView.  Note that we enabled paging and set the page size to 5.  We did not specify the pager type to custom because the default value is set to our custom pager.  If we wanted to revert to the GridViews built-in paging, we would set PagerType="Regular".  The only thing left to do is handle the OnPageIndexChanging to rebind our GridView to the new page via our code behind and that's it.

    Private Sub PagingGridView1_PageIndexChanging(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewPageEventArgs) Handles PagingGridView1.PageIndexChanging
        Me.PagingGridView1.PageIndex = e.NewPageIndex
        PagingGridView1_DataBind()
    End Sub

I hope you enjoyed this post.  It definitely has improved developer productivity without having to define a pager template and wire in the controls everytime I use the GridView.  The final screenshot of the PagingGridView is below.

GridViewPaging_Soln.zip (108.06 kb)

Bookmark and Share