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
Solved

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

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

DevOps Toolchain Recommendations

Read this Gartner Research Note and discover how your IT organization can automate and optimize DevOps processes using a toolchain architecture.

Question has a verified solution.

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

Wouldn’t it be nice if you could test whether an element is contained in an array by using a Contains method just like the one available on List objects? Wouldn’t it be good if you could write code like this? (CODE) In .NET 3.5, this is possible…
Real-time is more about the business, not the technology. In day-to-day life, to make real-time decisions like buying or investing, business needs the latest information(e.g. Gold Rate/Stock Rate). Unlike traditional days, you need not wait for a fe…
Microsoft Active Directory, the widely used IT infrastructure, is known for its high risk of credential theft. The best way to test your Active Directory’s vulnerabilities to pass-the-ticket, pass-the-hash, privilege escalation, and malware attacks …

840 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