Solved

VB.Net/DataGrid/DataView/Sort: Sorting columns by clicking on column heading not working

Posted on 2004-04-26
3
1,683 Views
Last Modified: 2008-09-12
I am working through creating my first datagrid by following an example in a book. I am currently trying to get sorting to work. My HTML and VB.Net code is below. The DataGrid loads with the data just fine. However, when I click on a column heading I get an error. I get the server error:

Object reference not set to an instance of an object.

When I set a breakpoint in the VB.Net code and then use the intermediate window to interrogate the errant line I get the following error description is:

Referenced object 'dview' has a value of 'Nothing'.

Below I have commented the line in the VB code where it bombs.  What's wrong here?

Thanks!
***************************************************************************

VB.NET Code
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Imports System.Web.UI
Imports System.Data
Imports System.Data.SqlClient

Public Class NPMSMain
    Inherits System.Web.UI.Page

 'These are used by multiple subs
    Dim dview As DataView
    Dim dsMsgs As DataSet

    Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

        If Not IsPostBack Then

            Dim cnn As SqlConnection
            Dim cmd As SqlCommand
            Dim Login As ASCXLogin
            Dim dad As SqlDataAdapter
            Dim strSQL As String

            Login = New ASCXLogin
            cnn = Login.GetConnection

            'Create SELECT for data adapter
            strSQL = "SELECT MsgID, Archive, Importance, CreatedByLoginID AS Author, CreateDate AS Date, Subject, SystemMsg "
            strSQL += "FROM NPMSMessageCenter WHERE "
            strSQL += "EID = " + CType(Session("EID"), String) + " AND "
            strSQL += "LoginID = " + CType(Session("LoginID"), String) + " AND "
            strSQL += "Archive = 0"

            'Create a dataset
            dsMsgs = New DataSet

            'Configure SQLDataAdapter and fill dataset
            dad = New SqlDataAdapter(strSQL, cnn)
            dad.Fill(dsMsgs, "Messages")

            'Create a dataview from the dataset
            dview = dsMsgs.Tables("Messages").DefaultView

            'Bind the dataview to the datagrid
            dgridMsgCenter.DataSource = dview
            dgridMsgCenter.DataBind()

        End If

    End Sub

    Sub dgridMsgCenter_SortCommand(ByVal s As Object, ByVal e As DataGridSortCommandEventArgs)

        dview.Sort = e.SortExpression              'CODE BOMBS ON THIS LINE
        dgridMsgCenter.DataSource = dview
        dgridMsgCenter.DataBind()

    End Sub

HTML Code
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
.
.
.
<body bgColor="white">
<form id="frmMessageCenter" method="post" runat="server">
<table cellSpacing="0" cellPadding="0" width="600" border="0">
<tr>
<td class="MCHeader"><FONT face="Arial" color="white" size="2">
<B>Message Center</B></FONT>
</td>
</tr>

<tr>
<td>
<asp:datagrid id="dgridMsgCenter" runat="server"
      PageSize="5"
      AllowPaging="True"
      AllowSorting="True"
      Width="600px"
      DataKeyField="MsgID"
      GridLines="Horizontal"
      CellPadding="0"
      BorderColor="Gray"
      ItemStyle-Font-Size="9pt"
      ItemStyle-Font-Name="Arial"
      OnSortCommand="dgridMsgCenter_SortCommand"  
      autogeneratecolumns="False">

      <AlternatingItemStyle BackColor="#EDF3FE"></AlternatingItemStyle>
      <ItemStyle Font-Size="9pt" Font-Names="Arial"></ItemStyle>
      <HeaderStyle Font-Size="9pt" Font-Names="Arial" Font-Bold="True" HorizontalAlign="Center" BackColor="Black">
                </HeaderStyle>

      <Columns>
      <asp:BoundColumn Visible="False" DataField="MsgID" HeaderText="ID"></asp:BoundColumn>
      <asp:ButtonColumn Text="Remove" ButtonType="PushButton" HeaderText="Remove"
                        CommandName="Delete"></asp:ButtonColumn>
      <asp:BoundColumn Visible="False" DataField="Archive" SortExpression="Archive" HeaderText="Arc">
                        </asp:BoundColumn>
      <asp:BoundColumn DataField="Importance" SortExpression="Importance" HeaderText="Imp">
      <HeaderStyle HorizontalAlign="Center" Width="30px"></HeaderStyle>
      <ItemStyle HorizontalAlign="Center"></ItemStyle>
      </asp:BoundColumn>
      <asp:BoundColumn DataField="Author" SortExpression="Date" HeaderText="From">
      <HeaderStyle HorizontalAlign="Center" Width="50px"></HeaderStyle>
      <ItemStyle HorizontalAlign="Center"></ItemStyle>
      </asp:BoundColumn>
      <asp:BoundColumn DataField="Subject" SortExpression="Subject" HeaderText="Subject">
      <HeaderStyle HorizontalAlign="Left" Width="425px"></HeaderStyle>
      <ItemStyle HorizontalAlign="Left"></ItemStyle>
      </asp:BoundColumn>
      <asp:BoundColumn DataField="Date" SortExpression="Date" HeaderText="Date" DataFormatString="{0:d}">
      <HeaderStyle HorizontalAlign="Center" Width="75px"></HeaderStyle>
      <ItemStyle HorizontalAlign="Center"></ItemStyle>
      </asp:BoundColumn>
      </Columns>
      <PagerStyle NextPageText="Next &gt;" Font-Size="9pt" Font-Names="Arial" Font-Bold="True" PrevPageText="&lt; Prev"
      HorizontalAlign="Center" ForeColor="Black" BackColor="Black"></PagerStyle>
</asp:datagrid>

0
Comment
Question by:rgrimm
3 Comments
 
LVL 28

Accepted Solution

by:
iboutchkine earned 250 total points
ID: 10927695
Private Sub dgrTitles_SortCommand(ByVal source As Object, ByVal e As System.Web.UI.WebControls.DataGridSortCommandEventArgs) Handles dgrTitles.SortCommand
        ' Extract current sort column and order.
        Dim currSortExpr As String = dgrTitles.Attributes("SortExpr")
        Dim newSortExpr As String = e.SortExpression

        ' If the sort expression is the same as the current one, just reverse the direction.
        If Not (currSortExpr Is Nothing) AndAlso currSortExpr.ToString = e.SortExpression Then
            newSortExpr &= " DESC"
        End If

        ' Remember the new sort expression and rebind.
        dgrTitles.Attributes("SortExpr") = newSortExpr
        BindDataGrid()
    End Sub

' Bind the DataGrid control.
    Sub BindDataGrid()
        ' Bind the data source to the DataGrid.
        dgrTitles.DataSource = ds.Tables("Titles")
        dgrTitles.DataKeyField = "title_id"

        ' Retrieve the SortExpression. This value is stored into the
        ' SortExpr attribute, so that its initial value can be edited
        ' directly in the HTML view
        Dim sortExpr As String = dgrTitles.Attributes("SortExpr")

        ' if the grid must be sorted, then we need to bind to a DataView
        ' instead of directly to the DataGrid

        If Not (sortExpr Is Nothing) AndAlso sortExpr.ToString.Length > 0 Then
            ' We must bind to a sorted DataView object instead.
            Dim dv As DataView = ds.Tables("Titles").DefaultView
            dv.Sort = sortExpr.ToString
            dgrTitles.DataSource = dv
        End If

        ' Do the binding.
        dgrTitles.DataBind()

        ' If we are in edit mode, also bind the ddlPublishers control.
        If dgrTitles.EditItemIndex >= 0 Then
            ' Get a reference to the ddlPublishers control.
            Dim dgi As DataGridItem = dgrTitles.Items(dgrTitles.EditItemIndex)
            Dim ddlPublishers As DropDownList = DirectCast(dgi.FindControl("ddlPublishers"), DropDownList)

            ' Bind it to the Publishers DataTable.
            ddlPublishers.DataSource = ds.Tables("Publishers")
            ddlPublishers.DataTextField = "pub_name"
            ddlPublishers.DataValueField = "pub_id"
            ddlPublishers.DataBind()

            ' Highlight the publisher of the current title
            Dim dr As DataRow = GetDataRow(dgrTitles.DataKeys(dgrTitles.EditItemIndex).ToString)
            SelectItemFromValue(ddlPublishers, dr("pub_id").ToString)
        End If

    End Sub
0

Featured Post

3 Use Cases for Connected Systems

Our Dev teams are like yours. They’re continually cranking out code for new features/bugs fixes, testing, deploying, testing some more, responding to production monitoring events and more. It’s complex. So, we thought you’d like to see what’s working for us.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Flash (http://en.wikipedia.org/wiki/Adobe_Flash) has evolved over the years to where it has become a masterful tool for displaying content screen.  It has excellent layout placement, UI precision as well as rendering capabilities. This, along with t…
This article shows how to deploy dynamic backgrounds to computers depending on the aspect ratio of display
This Micro Tutorial hows how you can integrate  Mac OSX to a Windows Active Directory Domain. Apple has made it easy to allow users to bind their macs to a windows domain with relative ease. The following video show how to bind OSX Mavericks to …
Nobody understands Phishing better than an anti-spam company. That’s why we are providing Phishing Awareness Training to our customers. According to a report by Verizon, only 3% of targeted users report malicious emails to management. With compan…

770 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question