DataGridView, Set up columns, Populate Data Table, Bind, but not using columns created in code?
Posted on 2011-10-26
I'm using VB.net 2005.
I have working programs that I populate DataGridViews with something like the following:
Public dt As DataTable
' Call BuildDataTable in Form_Load
Private Sub BuildDataTable()
Private Sub FillDataTable()
Dim QueRow As DataRow
'Query SQL server table here, Rdr = cmd.ExecuteReader(), and loop/populate DataTable...
Do While Rdr.Read() = True ' This automatically advances records until EOF
QueRow = dt.NewRow
QueRow.Item("Que#") = Rdr.Item("Queue#")
QueRow.Item("TrimCat#") = Rdr.Item("TrimCat#")
QueRow.Item("Lockside") = RTrim(Rdr.Item("LockSideRabbet"))
' Bind DataGridView to DataSource
dgvQueue.DataSource = dt
So the above works just fine. It automatically creates the colums and populates them with the data. Here's my new scenerio / question. I want to have more control over the columns and make one of them a DataGridViewButtonColumn (in code, not in GUI). So I added code as follows:
c1 = New DataGridViewTextBoxColumn()
c1.Name = "Que##"
c2 = New DataGridViewButtonColumn()
c2.Name = "TrimCat"
c2.Text = "Click Here"
c2.HeaderText = "Status-btn"
c2.UseColumnTextForButtonValue = True
c3 = New DataGridViewTextBoxColumn()
c3.Name = "Lock"
So now when it runs I get the the 3 colums/fields I added in Form_Load (and they are empty) followed by the original 3 fields I built from DataTable. What I was hoping would happen was the 3 fields/columns from the DataTable would populate the columns I created in Form_Load.
My questions: Is there a simple way to make the columns I created in Form_Load populate with the data from the DataTable?
Or maybe I am going about this wrong. Instead of populating the DateTable with my query results in the loop and then binding the DataTable to the DataGridView, instead should I be populating the DataGridView direclty and not use a DataTable? (Not sure how to do that.)
Code samples please...