1

Why doesn't my DataGridView have an index row or first row on the first load form in vb.net.

is there something wrong with my code?

Thanks

Public Class Form1
     Private itemtransfer As New List(Of ItemTransfer)()
    Private Sub AddColumnsProgrammatically()
        Dim col1 = New DataGridViewTextBoxColumn()
        Dim col2 = New DataGridViewTextBoxColumn()
        col1.HeaderText = "No"
        col1.Name = "No"
        col1.DataPropertyName = "No"
        col2.HeaderText = "CodeProduct"
        col2.Name = "CodeProduct"
        col2.DataPropertyName = "CodeProduct"
        DataGridView1.Columns.AddRange(New DataGridViewColumn() {col1, col2})
    End Sub
    Private Sub LoadData()
        DataGridView1.DataSource = itemtransfer
    End Sub
 Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        AddColumnsProgrammatically()
        LoadData()
    End Sub
Public Class ItemTransfer
    Public Property No() As Integer
    Public Property CodeProduct() As String
End Class

datagridview don't have row index or first row

first row blank datagridview

roy
  • 693
  • 2
  • 11
  • 1
    First things first, `itemtransfer` is a terrible name for that field. It's generally a bad idea to name a variable after its type because it can cause confusion. Apart from that, variables that refer to arrays or collections should have pluralised names, because they are intended to hold multiple objects. `itemTransfers` is the obvious choice of name for that field. – jmcilhinney Jun 20 '23 at 08:28
  • Where in that code do you add any items to your list? Nowhere that I can see. If you add no items, why would you expect any items to be displayed? – jmcilhinney Jun 20 '23 at 08:31
  • @jmcilhinney , It should appear a blank first row like the screenshot I attached. – roy Jun 20 '23 at 08:44
  • @jmcilhinney , `because they are intended to hold multiple objects. itemTransfers is the obvious choice of name for that field` I agree with you. It should be plural – roy Jun 20 '23 at 08:46

1 Answers1

1

That row in your second screenshot is the data entry row, where new records are entered. For that to be present, you must have AllowUserToAddRows set to True and, if the grid is bound, the DataSource must be an IBindingList with AllowNew set to True. You are binding your grid to a List(Of T), so it doesn't meet those criteria. It doesn't have all the members required for data binding to work fully. You should create a BindingList(Of T) instead if you want that.

jmcilhinney
  • 50,448
  • 5
  • 26
  • 46