按十进制排序DataGridView

时间:2018-07-29 20:53:23

标签: vb.net datagridview sqlite

我知道有很多这样的帖子,但是我找不到正确的解决方案。我需要以升序对datagridview的第一列进行排序。但是排序顺序是错误的。第一列是主键,包含十进制值。

下面是我的示例代码。在填充列之后,我尝试更改数据类型,但是它不起作用。

Imports System.Data.SQLite

Public Class Form1

Dim conn As SQLiteConnection
Dim da As SQLiteDataAdapter
Dim table As New DataTable
Dim cmdbl As SQLiteCommandBuilder


Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load

    Const filename As String = "database.db"
    conn = New SQLiteConnection("Data Source=" & filename & ";Version=3;")
    conn.Open()
    Dim sql As String = "select * from 'item_rate' ORDER BY 'SL NO' ASC"

    da = New SQLiteDataAdapter(sql, conn)
    da.Fill(table)
    DataGridView1.DataSource = table
    DataGridView1.Columns(0).CellTemplate.ValueType = GetType(Decimal)
    DataGridView1.Sort(DataGridView1.Columns(0), 0)


End Sub

1 个答案:

答案 0 :(得分:0)

我终于找到了解决方案。而不是更改DGV的列数据类型,而是更改DataTable的列数据类型。为此,您需要克隆DataTable并更改列Datatype。表填充数据后,您将无法更改数据类型。下面是示例代码。

Imports System.Data.SQLite

Public Class Form1

Dim conn As SQLiteConnection
Dim da As SQLiteDataAdapter
Dim table As New DataTable
Dim cmdbl As SQLiteCommandBuilder


Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load

    Const filename As String = "database.db"
    conn = New SQLiteConnection("Data Source=" & filename & ";Version=3;")
    conn.Open()
    Dim sql As String = "select * from 'item_rate'"

    da = New SQLiteDataAdapter(sql, conn)
    da.Fill(table)

    'clone the DataTable to change the data type of a column for sorting

    Dim dtCloned As DataTable = table.Clone()
    dtCloned.Columns(0).DataType = GetType(Single) 'Assign the first column to decimal type AKA Single
    For Each row As DataRow In table.Rows
        dtCloned.ImportRow(row)
    Next
    'End Of Clone Table

    'Assign cloned table to DGV
    DataGridView1.DataSource = dtCloned
    'Sort DGV
    DataGridView1.Sort(DataGridView1.Columns(0), 0)

End Sub