I have the following code and I want to bind it to a DataGridView
.
Public Class Form1
Private _myTable As New DataTable()
Private Sub LoadData()
Dim item As New List(Of item())
Grid.Bind(item)
End Sub
Private Sub FillDataTable(iRow As Integer, ByVal Codeproduct As String)
_myTable.Columns.Add("No", GetType(Integer))
_myTable.Columns.Add("Codeproduct", GetType(String))
Dim row As DataRow = _myTable.NewRow()
row("No") = iRow
row("Codeproduct") = Codeproduct
_myTable.Rows.Add(row)
End Sub
Private Sub AddColumnsProgrammatically()
Dim Col1 = New DataGridViewTextBoxColumn()
Dim Col2 = New DataGridViewTextBoxColumn()
Col1.HeaderText = "No"
Col1.Name = "Column1"
Col1.DataPropertyName = "No"
Col2.HeaderText = "CodeProduct"
Col2.Name = "Column2"
Col2.DataPropertyName = "CodeProduct"
Grid.Columns.AddRange(New DataGridViewColumn() {Col1, Col2})
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
AddColumnsProgrammatically()
LoadData()
End Sub
Private Sub TextBox1_KeyPress(sender As Object, e As KeyPressEventArgs) Handles TextBox1.KeyPress
Dim iRow As Integer
If Grid.RowCount - 1 = 0 Then
iRow = 1
Else
iRow = Convert.ToInt32(Grid.Rows(Grid.RowCount - 2).Cells(0).Value.ToString()) + 1
End If
If e.KeyChar = Microsoft.VisualBasic.ChrW(Keys.Enter) Then
FillDataTable(iRow, TextBox1.Text)
Grid.DataSource = _myTable
TextBox1.Clear()
End If
End Sub
End Class
Public Class DataControl
Public Shared Function CreateDataTableDynamic(ByVal field() As String) As DataTable
Dim i As Integer
Dim dtTable As New DataTable("MyTable")
For i = 0 To field.GetUpperBound(0)
dtTable.Columns.Add(New DataColumn(field(i)))
Next i
Return dtTable
End Function
End Class
Public Class item
Public Property No() As Integer
Public Property CodeProduct() As String
End Class
I want to ask if there is anything wrong with my code, and how can I bind my DataGridView
to this data properly.
after add code "Columns.Add" and Fill the textbox in the second fill to DataGridView but still error
error when Fill the textbox in the second to DataGridView
[ breakpoint with diagnostic tool
[
In accordance with the guidelines of @jmcilhinney
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
_myTable.Columns.Add("No", GetType(Integer))
_myTable.Columns.Add("Codeproduct", GetType(String))
AddColumnsProgrammatically()
LoadData()
End Sub