Solved

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

Posted on 2004-04-26
3
1,675 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
Comment Utility
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

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

For those of you who don't follow the news, or just happen to live under rocks, Microsoft Research released a beta SDK (http://www.microsoft.com/en-us/download/details.aspx?id=27876) for the Xbox 360 Kinect. If you don't know what a Kinect is (http:…
Today I had a very interesting conundrum that had to get solved quickly. Needless to say, it wasn't resolved quickly because when we needed it we were very rushed, but as soon as the conference call was over and I took a step back I saw the correct …
In this seventh video of the Xpdf series, we discuss and demonstrate the PDFfonts utility, which lists all the fonts used in a PDF file. It does this via a command line interface, making it suitable for use in programs, scripts, batch files — any pl…
You have products, that come in variants and want to set different prices for them? Watch this micro tutorial that describes how to configure prices for Magento super attributes. Assigning simple products to configurable: We assigned simple products…

772 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

Need Help in Real-Time?

Connect with top rated Experts

9 Experts available now in Live!

Get 1:1 Help Now