Home > OS >  Add Row with Sequential Row # in VB.Net DataSet
Add Row with Sequential Row # in VB.Net DataSet

Time:02-24

I am trying to add rows using an "Add Row" Button from Windows Forms and I want to have it add Row number as well but in sequential order. So if the last row # was 9 I want it to add row #10 when I press the button.

I have it set up now so it simply adds a blank row using

Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
    dt.Rows.Add()
    DataGridView1.DataSource = dt
End Sub

How would I go about making it recognize the order and then create the next row in the sequence

Here is a picture of the design enter image description here

Here is the way I fill my datagridview using sql

 Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    Dim connection As New SqlConnection("Connection String Placeholder")
    Dim Table As New DataTable()
    Dim Adapter As New SqlDataAdapter("SELECT * FROM TrackMain$", connection)
    Adapter.Fill(Table)
    DataGridView1.DataSource = Table

    bind_data()


End Sub

CodePudding user response:

Basiclly, you can get the next row number in Form.Load event.

Private nextId As Integer = 0
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    ...
    bind_data()
    nextId = Convert.ToInt32(dt.Rows(dt.Rows.Count - 1)(0))   1
End Sub

Then set the row number when adding a new row:

Private Sub AddRowBtn_Click(sender As Object, e As EventArgs) Handles AddRowBtn.Click
    Dim dr As DataRow = dt.NewRow()
    dr(0) = nextId
    dt.Rows.Add(dr)
    nextId  = 1
End Sub
  • Related