?
Solved

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

Posted on 2004-04-26
3
Medium Priority
?
1,699 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
3 Comments
 
LVL 28

Accepted Solution

by:
iboutchkine earned 1000 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

Veeam Disaster Recovery in Microsoft Azure

Veeam PN for Microsoft Azure is a FREE solution designed to simplify and automate the setup of a DR site in Microsoft Azure using lightweight software-defined networking. It reduces the complexity of VPN deployments and is designed for businesses of ALL sizes.

Question has a verified solution.

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

IP addresses can be stored in a database in any of several ways.  These ways may vary based on the volume of the data.  I was dealing with quite a large amount of data for user authentication purpose, and needed a way to minimize the storage.   …
In my previous two articles we discussed Binary Serialization (http://www.experts-exchange.com/A_4362.html) and XML Serialization (http://www.experts-exchange.com/A_4425.html). In this article we will try to know more about SOAP (Simple Object Acces…
In this brief tutorial Pawel from AdRem Software explains how you can quickly find out which services are running on your network, or what are the IP addresses of servers responsible for each service. Software used is freeware NetCrunch Tools (https…
This is my first video review of Microsoft Bookings, I will be doing a part two with a bit more information, but wanted to get this out to you folks.
Suggested Courses

752 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