How to add auto increment number on my new column VB.NET

My Datagridview contains data's from my database and I Added new column but i want to insert auto increment number in this column how to do it.

Here's my code for my newly added column

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
    End With

End Sub

1 answer

  • answered 2018-10-17 08:59 jmcilhinney

    Rather than add an unbound column to your DataGridView, add an extra DataColumn to your DataTable. That can be set to auto-increment, e.g.

    Dim table As New DataTable
    Using adapter As New MySqlDataAdapter("SELECT * FROM MyTable", "connection string here")
        adapter.MissingSchemaAction = MissingSchemaAction.AddWithKey
        '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.
    End Using

    Now you have the column ready to go when you bind and you don't need any extra code to generate the values.