[RESOLVED] Sorting question for DataGridView
I have an application that reads an XML file into a dataset and binds that dataset to a DataGridView. It's not elegant, but it works.
Now, I know the user can click on a column and sort the data in ascending or descending order, but when the application starts the data is unsorted. What I want to do is set up a default sort, but I can't figure out how to do this programatically.
Any suggestions?
Re: Sorting question for DataGridView
Okay, just letting you know that I figured it out. Added this code right after the datatable was bound to the datagridview.
Code:
myGrid.Sort(myGrid.Columns("LastName"), System.ComponentModel.ListSortDirection.Ascending);
Re: [RESOLVED] Sorting question for DataGridView
Another way is to use a BindingSource
Code:
Public Class Form1
Private ds As New DataSet
Private bsOrders As New BindingSource
Private Sub Form1_Load(
ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles MyBase.Load
ds.ReadXml("Orders.xml")
bsOrders.DataSource = ds.Tables(0)
bsOrders.Sort = "LastName"
DataGridView1.DataSource = bsOrders
End Sub
End Class
Orders.xml
Code:
<?xml version="1.0" encoding="utf-8" ?>
<Orders>
<Order>
<Identifier>1</Identifier>
<LastName>Smith</LastName>
<OrderID>5</OrderID>
<Amount>25.00</Amount>
</Order>
<Order>
<Identifier>2</Identifier>
<LastName>Jones</LastName>
<OrderID>100</OrderID>
<Amount>1000.00</Amount>
</Order>
<Order>
<Identifier>3</Identifier>
<LastName>Brown</LastName>
<OrderID>9</OrderID>
<Amount>11.00</Amount>
</Order>
<Order>
<Identifier>4</Identifier>
<LastName>Caffery</LastName>
<OrderID>12</OrderID>
<Amount>7.00</Amount>
</Order>
<Order>
<Identifier>5</Identifier>
<LastName>Jacobe</LastName>
<OrderID>12</OrderID>
<Amount>512.00</Amount>
</Order>
</Orders>
Or DataView
Code:
Public Class Form1
Private ds As New DataSet
Private Sub Form1_Load(
ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles MyBase.Load
ds.ReadXml("Orders.xml")
Dim dv = ds.Tables(0).DefaultView
dv.Sort = "LastName"
DataGridView1.DataSource = dv
End Sub
End Class