VB.NET - Add Rows and Columns to a DataGrid



Adds Rows and Columns to a DataGrid using a DataSet and a BindingSource

'Assembly: System.Data.dll
'Assembly: System.Windows.Forms.dll
'Assembly: System.Xml

'Namespace: System.Data
'Namespace: System.Windows.Forms
'Namespace: System
'Namespace: Microsoft.VisualBasic

'Dim DataGrid AS System.Windows.Forms.DataGrid

' Create a DataSet for binding to a 
' DataGrid using a BindingSource object.
   Private Sub SetUpDataGrid()
      Dim BindingSource1 As New BindingSource

     ' Create a DataSet with a 
     ' table of customer sales data.
      Dim myDataSet As New DataSet("myDataSet")
      Dim tSales As New DataTable("Sales")
      
      ' Add three columns.
      Dim colDate As New DataColumn("Date", GetType(DateTime))
      Dim colCust As New DataColumn("Customer")
      Dim colTotal As New DataColumn("Total", GetType(Decimal))
      tSales.Columns.Add(colDate)
      tSales.Columns.Add(colCust)
      tSales.Columns.Add(colTotal)
       
      ' Add the table to the DataSet.
      myDataSet.Tables.Add(tSales)
        
      'Add needed rows. 
      Dim newRow As DataRow
      Dim i As Integer
      For i = 1 To 3
         newRow = tSales.NewRow()
         tSales.Rows.Add(newRow)
      Next i

      ' Populate the table withe customer data.
      tSales.Rows(0)("Date") = DateTime.Today
      tSales.Rows(0)("Customer") = "Parker, Darren"
      tSales.Rows(0)("Total") = 123.23

      tSales.Rows(1)("Date") = DateTime.Today
      tSales.Rows(1)("Customer") = "Ji, Jeune"
      tSales.Rows(1)("Total") = 4322.33

      tSales.Rows(2)("Date") = DateTime.Today
      tSales.Rows(2)("Customer") = "Tibbott, Diane"
      tSales.Rows(2)("Total") = 1222.33

      ' Set the BindingSource to the DataSet.      
      BindingSource1.DataSource = myDataSet

      ' Bind the DataGrid to the BindingSource.
      DataGrid.DataSource = BindingSource1

      ' Set the current binding item to the Sales table.
      BindingSource1.DataMember = "Sales"
   End Sub 

Share |

 Cant find the page you are looking for?
 Help us to improve by adding the content that you are looking for.
 Leave a feedback
 We look forward to hear your comments and feedback.