Hi dnnyobi,
Read the data from Access Database to Datatable. Then apply the Order By clause for sorting.
Populate TreeView from Database in Windows Forms using C# and VB.Net
Using the above article i have created by adding some special alphabets and apply the ordering.
Refer below example.
Namespaces
C#
using System.Data;
using System.Data.SqlClient;
VB.Net
Imports System.Data
Imports System.Data.SqlClient
Code
C#
private void Form1_Load(object sender, EventArgs e)
{
DataTable dt = this.GetData("SELECT Id, Name FROM VehicleTypes");
dt.Rows.Add("4", "C");
dt.Rows.Add("5", "Z");
dt.Rows.Add("6", "Ị");
dt.Rows.Add("7", "I");
dt.Rows.Add("8", "Ị");
dt.Rows.Add("9", "Ẹ");
dt.Rows.Add("10", "Ị");
dt = dt.AsEnumerable().OrderBy(x => x.Field<string>("Name")).CopyToDataTable();
foreach (DataRow row in dt.Rows)
{
treeView1.Nodes.Add(new TreeNode
{
Text = row["Name"].ToString(),
Tag = row["Id"]
});
}
}
private DataTable GetData(string query)
{
string constr = @"Data Source=.\SQL2019;Initial Catalog=VehiclesDB;UID=sa;PWD=pass@123";
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlDataAdapter sda = new SqlDataAdapter(query, con))
{
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
return dt;
}
}
}
}
VB.Net
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
Dim dt As DataTable = Me.GetData("SELECT Id, Name FROM VehicleTypes")
dt.Rows.Add("4", "C")
dt.Rows.Add("5", "Z")
dt.Rows.Add("6", "Ị")
dt.Rows.Add("7", "I")
dt.Rows.Add("8", "Ị")
dt.Rows.Add("9", "Ẹ")
dt.Rows.Add("10", "Ị")
dt = dt.AsEnumerable().OrderBy(Function(x) x.Field(Of String)("Name")).CopyToDataTable()
For Each row As DataRow In dt.Rows
treeView1.Nodes.Add(New TreeNode() With {
.Text = row("Name").ToString(),
.Tag = row("Id")
})
Next
End Sub
Private Function GetData(query As String) As DataTable
Dim constr As String = "Data Source=.\SQL2019;Initial Catalog=VehiclesDB;UID=sa;PWD=pass@123"
Using con As New SqlConnection(constr)
Using sda As New SqlDataAdapter(query, con)
Using dt As New DataTable()
sda.Fill(dt)
Return dt
End Using
End Using
End Using
End Function
Screenshot
