Solved

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

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

Webinar: Aligning, Automating, Winning

Join Dan Russo, Senior Manager of Operations Intelligence, for an in-depth discussion on how Dealertrack, leading provider of integrated digital solutions for the automotive industry, transformed their DevOps processes to increase collaboration and move with greater velocity.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
How to seperate number and letters from a string 3 25
Groupbox Control ? 2 29
VB.Net SQL Query 2 Tables Different Databases 3 45
Convert VB web project to C# 3 39
Summary Displaying images in RichTextBox is a common requirement with limited solutions available. Pasting through clipboard or embedding into RTF content only support static images.  This article describes how to insert Windows control objects int…
This document covers how to connect to SQL Server and browse its contents.  It is meant for those new to Visual Studio and/or working with Microsoft SQL Server.  It is not a guide to building SQL Server database connections in your code.  This is mo…
In an interesting question (https://www.experts-exchange.com/questions/29008360/) here at Experts Exchange, a member asked how to split a single image into multiple images. The primary usage for this is to place many photographs on a flatbed scanner…

733 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