如何在我的新列vb.net上添加自动递增数字

ercv8c1e  于 2021-06-20  发布在  Mysql
关注(0)|答案(1)|浏览(367)

我的datagridview包含数据库中的数据,我添加了新列,但我想在这个列中插入自动递增的数字如何做。
这是我新添加的专栏的代码

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

    Dim idcolumn As New DataGridViewTextBoxColumn

    With idcolumn
        .HeaderText = "ID"
        .Name = "ID"

    End With

     Dim count as Integer  ="1"
    count = Val(count) +1
    With DataGridView1
        .Columns.Add(idcolumn)
    End With

末端接头

mhd8tkvw

mhd8tkvw1#

而不是将未绑定的列添加到 DataGridView ,添加一个额外的 DataColumn 给你的 DataTable . 可以设置为自动递增,例如。

Dim table As New DataTable

Using adapter As New MySqlDataAdapter("SELECT * FROM MyTable", "connection string here")
    adapter.MissingSchemaAction = MissingSchemaAction.AddWithKey
    adapter.SelectCommand.Connection.Open()

    'Get the schema from the database without the data.
    adapter.FillSchema(table, SchemaType.Source)

    'Add an auto-incrementing column to the table.
    With table.Columns.Add("ID", GetType(Integer))
        .AutoIncrementSeed = 1
        .AutoIncrementStep = 1
        .AutoIncrement = True
    End With

    'Get the data.
    adapter.Fill(table)
End Using

现在,在绑定时,列已经准备就绪,不需要任何额外的代码来生成值。

相关问题