如何在我的新列VB.NET上添加自动递增编号

时间:2018-10-17 07:23:40

标签: mysql vb.net

我的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

结束子

1 个答案:

答案 0 :(得分:0)

除了向您的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

现在,绑定后就可以使用该列了,并且不需要任何其他代码即可生成值。