Gridview help with sorting

siraero

Active member
Joined
Jan 21, 2012
Messages
32
Programming Experience
Beginner
Hi.
Im new to this but have found a C# ex. for sorting that i have converted to VB.
If i just run the code with my db connection in Page_Load to the gridview i get the data i need, but if im trying to make a sorting
code, then im not getting anydata, i have a clean page_load and i have the connection in a function called GetData()
Can someone help me fixing the last things/guide me, so i can get it to work.
My code is
Main code:
Code:
<%@ Page Language="VB" AutoEventWireup="false" CodeFile="default.aspx.vb" Inherits="_default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    
        <asp:GridView ID="MySource" runat="server" CellPadding="4" ForeColor="#333333" GridLines="None" AutoGenerateColumns="False" DataKeyNames="email_id" AllowPaging="True" emptydatatext="Ingen Data tilgængelig." allowsorting="true" EnableViewState="False" OnRowCreated="MySource_RowCreated" OnSorting="MySource_Sorting">
            <AlternatingRowStyle BackColor="White" />
            <EditRowStyle BackColor="#2461BF" />
            <FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
            <HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
            <PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
            <RowStyle BackColor="#EFF3FB" />
            <SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
            <SortedAscendingCellStyle BackColor="#F5F7FB" />
            <SortedAscendingHeaderStyle BackColor="#6D95E1" />
            <SortedDescendingCellStyle BackColor="#E9EBEF" />
            <SortedDescendingHeaderStyle BackColor="#4870BE" />
            <Columns>
                <asp:TemplateField HeaderText="Vælg">
                    <ItemTemplate>
                        <asp:CheckBox ID="CheckBox1" runat="server" />
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:BoundField DataField="email_name" HeaderText="Navn" SortExpression="email_name" />
                <asp:BoundField DataField="email_gen" HeaderText="Køn" SortExpression="email_gen" />
                <asp:BoundField DataField="email_old" DataFormatString="{0:d}" HeaderText="Alder" SortExpression="email_old" />
                <asp:BoundField DataField="email_adr" HeaderText="EmailADR" />
            </Columns>

        </asp:GridView>
    
    </div>
    </form>
</body>
</html>
Code_Behind:
Code:
Imports System.IO
Imports System.Data
Imports System.Data.OleDb

Partial Class _default
    Inherits System.Web.UI.Page

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load






    End Sub


    <Serializable()> _
    Public Class EmailList
        Private _email_name As String
        Private _email_gen As String
        Private _email_old As DateTime
        Private _email_adr As String

        Public Sub New()
        End Sub

        Public Property email_name() As String
            Get
                Return _email_name
            End Get
            Set(value As String)
                _email_name = value
            End Set
        End Property

        Public Property email_gen() As String
            Get
                Return _email_gen
            End Get

            Set(value As String)
                _email_gen = value
            End Set
        End Property

        Public Property [email_old]() As DateTime
            Get
                Return _email_old
            End Get

            Set(value As DateTime)
                _email_old = value
            End Set
        End Property

        Public Property email_adr() As String
            Get
                Return _email_adr
            End Get

            Set(value As String)
                _email_adr = value
            End Set
        End Property
    End Class


    Private Const ASCENDING As String = " ASC"
    Private Const DESCENDING As String = " DESC"
    Protected Sub MySource_Sorting(sender As Object, e As GridViewSortEventArgs)
        Dim sortExpression As String = e.SortExpression
        ViewState("SortExpression") = sortExpression
        If GridViewSortDirection = SortDirection.Ascending Then
            GridViewSortDirection = SortDirection.Descending
            SortGridView(sortExpression, DESCENDING)
        Else
            GridViewSortDirection = SortDirection.Ascending
            SortGridView(sortExpression, ASCENDING)
        End If
    End Sub


    Private Property GridViewSortDirection() As SortDirection
        Get
            If ViewState("sortDirection") Is Nothing Then
                ViewState("sortDirection") = SortDirection.Ascending
            End If
            Return DirectCast(ViewState("sortDirection"), SortDirection)
        End Get

        Set(value As SortDirection)
            ViewState("sortDirection") = value
        End Set
    End Property


    Private Sub SortGridView(sortExpression As String, direction As String)
        Dim EmailCheck As ArrayList = DirectCast(ViewState("EmailCheck"), ArrayList)
        Dim dt As New DataTable()
        dt.Columns.Add("email_name")
        dt.Columns.Add("email_gen")
        dt.Columns.Add("email_old")
        dt.Columns("email_old").DataType = System.Type.[GetType]("System.DateTime")
        dt.Columns.Add("email_adr")

        For Each email As EmailList In EmailCheck
            Dim dr As DataRow = dt.NewRow()
            dr("Navn") = email.email_name()
            dr("Køn") = email.email_gen()
            dr("Alder") = email.email_old()
            dr("EmailADR") = email.email_adr()
            dt.Rows.Add(dr)
        Next

        Dim dv As New DataView(dt)
        dv.Sort = sortExpression & direction
        MySource.DataSource = dv
        MySource.DataBind()
    End Sub


    Protected Sub MySource_RowCreated(sender As Object, e As GridViewRowEventArgs)
        If e.Row.RowType = DataControlRowType.Header Then
            Dim sortColumnIndex As Integer = GetSortColumnIndex()
            If sortColumnIndex <> -1 Then
                AddSortImage(sortColumnIndex, e.Row)
            End If
        End If
    End Sub


    Private Function GetSortColumnIndex() As Integer
        For Each field As DataControlField In MySource.Columns
            If field.SortExpression = DirectCast(ViewState("SortExpression"), String) Then
                Return MySource.Columns.IndexOf(field)
            End If
        Next

        Return -1
    End Function


    Private Sub AddSortImage(columnIndex As Integer, headerRow As GridViewRow)
        ' Create the sorting image based on the sort direction.
        Dim sortImage As New Image()
        If GridViewSortDirection = SortDirection.Ascending Then
            sortImage.ImageUrl = "~/images/sort_asc_arrow.gif"
            sortImage.AlternateText = "Ascending Order"
        Else
            sortImage.ImageUrl = "~/images/sort_desc_arrow.gif"
            sortImage.AlternateText = "Descending Order"
        End If
        ' Add the image to the appropriate header cell.
        headerRow.Cells(columnIndex).Controls.Add(sortImage)
    End Sub


    Private Function GetData() As DataSet
        'Get data from DB using DataSet 
        Using connection As OleDbConnection = New OleDbConnection(ConfigurationManager.ConnectionStrings("MyConnStr").ConnectionString)
            Dim sql As String = "select * from email_list"
            Using adapter As OleDbDataAdapter = New OleDbDataAdapter(sql, connection)
                Dim ds As New DataSet()
                adapter.Fill(ds)
                Return ds
                'MySource.DataSource = ds
                'MySource.DataBind()
            End Using
        End Using
    End Function

End Class
Thx alot...
 

nayanpatel

Active member
Joined
Nov 18, 2016
Messages
27
Location
ahmedabad
Programming Experience
3-5
The following example demonstrates how to use the AllowSorting property to enable sorting in a GridView control when automatically generated columns are used.



<%@ Page language="VB" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>GridView AllowSorting Example</title>
</head>
<body>
<form id="form1" runat="server">

<h3>GridView AllowSorting Example</h3>

<asp:gridview id="CustomersGridView"
datasourceid="CustomersSource"
autogeneratecolumns="true"
emptydatatext="No data available."
allowsorting="true"
runat="server">

</asp:gridview>

<!-- This example uses Microsoft SQL Server and connects -->
<!-- to the Northwind sample database. Use an ASP.NET -->
<!-- expression to retrieve the connection string value -->
<!-- from the Web.config file. -->
<asp:sqldatasource id="CustomersSource"
selectcommand="Select [CustomerID], [CompanyName], [Address], [City], [PostalCode], [Country] From [Customers]"
connectionstring="<%$ ConnectionStrings:NorthWindConnectionString%>"
runat="server"/>

</form>
</body>
</html>
The following example demonstrates how to use the AllowSorting property to enable sorting in a GridView control when a Columns collection is defined. An image is also programmatically added to the header of the column being sorted to indicate the sort direction. You must provide your own images for this sample to work.
<%@ Page language="VB" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">

Sub CustomersGridView_RowCreated(ByVal sender As Object, ByVal e As GridViewRowEventArgs)

' Use the RowType property to determine whether the
' row being created is the header row.
If e.Row.RowType = DataControlRowType.Header Then

' Call the GetSortColumnIndex helper method to determine
' the index of the column being sorted.
Dim sortColumnIndex As Integer = GetSortColumnIndex()

If sortColumnIndex <> -1 Then

' Call the AddSortImage helper method to add
' a sort direction image to the appropriate
' column header.
AddSortImage(sortColumnIndex, e.Row)

End If

End If

End Sub

' This is a helper method used to determine the index of the
' column being sorted. If no column is being sorted, -1 is returned.
Function GetSortColumnIndex() As Integer

' Iterate through the Columns collection to determine the index
' of the column being sorted.
Dim field As DataControlField
For Each field In CustomersGridView.Columns

If field.SortExpression = CustomersGridView.SortExpression Then

Return CustomersGridView.Columns.IndexOf(field)

End If

Next

Return -1

End Function

' This is a helper method used to add a sort direction
' image to the header of the column being sorted.
Sub AddSortImage(ByVal columnIndex As Integer, ByVal row As GridViewRow)

' Create the sorting image based on the sort direction.
Dim sortImage As New Image()
If CustomersGridView.SortDirection = SortDirection.Ascending Then

sortImage.ImageUrl = "~/Images/Ascending.jpg"
sortImage.AlternateText = "Ascending Order"

Else

sortImage.ImageUrl = "~/Images/Descending.jpg"
sortImage.AlternateText = "Descending Order"

End If
' Add the image to the appropriate header cell.
row.Cells(columnIndex).Controls.Add(sortImage)

End Sub

</script>

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>GridView AllowSorting Example</title>
</head>
<body>
<form id="form1" runat="server">

<h3>GridView AllowSorting Example</h3>

<asp:gridview id="CustomersGridView"
datasourceid="CustomersSource"
autogeneratecolumns="false"
emptydatatext="No data available."
allowsorting="true"
onrowcreated="CustomersGridView_RowCreated"
runat="server">

<columns>
<asp:boundfield datafield="CustomerID"
headertext="Customer ID"
headerstyle-wrap="false"
sortexpression="CustomerID"/>
<asp:boundfield datafield="CompanyName"
headertext="CompanyName"
headerstyle-wrap="false"
sortexpression="CompanyName"/>
<asp:boundfield datafield="Address"
headertext="Address"
headerstyle-wrap="false"
sortexpression="Address"/>
<asp:boundfield datafield="City"
headertext="City"
headerstyle-wrap="false"
sortexpression="City"/>
<asp:boundfield datafield="PostalCode"
headertext="Postal Code"
headerstyle-wrap="false"
sortexpression="PostalCode" />
<asp:boundfield datafield="Country"
headertext="Country"
headerstyle-wrap="false"
sortexpression="Country"/>
</columns>

</asp:gridview>

<!-- This example uses Microsoft SQL Server and connects -->
<!-- to the Northwind sample database. Use an ASP.NET -->
<!-- expression to retrieve the connection string value -->
<!-- from the Web.config file. -->
<asp:sqldatasource id="CustomersSource"
selectcommand="Select [CustomerID], [CompanyName], [Address], [City], [PostalCode], [Country] From [Customers]"
connectionstring="<%$ ConnectionStrings:NorthWindConnectionString%>"
runat="server"/>

</form>
</body>
</html>
 
Top Bottom