?
Solved

DataGridView, Set up columns, Populate Data Table, Bind, but not using columns created in code?

Posted on 2011-10-26
10
Medium Priority
?
778 Views
Last Modified: 2012-05-12
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()
        dt.Columns.Add("Que#", Type.GetType("System.Int16"))
        dt.Columns.Add("TrimCat#", Type.GetType("System.String"))
        dt.Columns.Add("Lockside", Type.GetType("System.String"))
End Sub
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"))
                dt.Rows.Add(QueRow)
            Loop
End Sub
 ' 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:

Form_Load
        c1 = New DataGridViewTextBoxColumn()
        c1.Name = "Que##"
        Me.dgvQueue.Columns.Add(c1)
        c2 =  New DataGridViewButtonColumn()
        c2.Name = "TrimCat"
        c2.Text = "Click Here"
        c2.HeaderText = "Status-btn"
        c2.UseColumnTextForButtonValue = True
        Me.dgvQueue.Columns.Add(c2)
        c3 = New DataGridViewTextBoxColumn()
        c3.Name = "Lock"
        Me.dgvQueue.Columns.Add(c3)
End Sub

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...

Thanks


0
Comment
Question by:sqdperu
  • 5
  • 5
10 Comments
 
LVL 17

Expert Comment

by:nepaluz
ID: 37031609
Do exactly as you were doing before adding the new column and after populating the datagridview, insert your button column, e.g
Private Sub BuildDataTable()
        dt.Columns.Add("Que#", Type.GetType("System.Int16"))
        dt.Columns.Add("TrimCat#", Type.GetType("System.String"))
        dt.Columns.Add("Lockside", Type.GetType("System.String"))
End Sub
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"))
                dt.Rows.Add(QueRow)
            Loop
End Sub
 ' Bind DataGridView to DataSource
 dgvQueue.DataSource = dt

Dim c2 As DataGridViewButtonColumn = New DataGridViewButtonColumn
c2.Name = "TrimCat"
c2.Text = "Click Here"
c2.HeaderText = "Status-btn"
c2.UseColumnTextForButtonValue = True
Me.dgvQueue.Columns.Insert(1, c2)

Open in new window

0
 

Author Comment

by:sqdperu
ID: 37031743
nepaluz,

Thanks for the advice.  But what that does is just add the column to the end with no real values pertaining to the data.  I know how to do that.  What I am trying to do is change the 2nd column, the column in the middle "TrimCat", to be a button column.  Then maybe I could add to the the code a condition where if the field is null, show the button, otherwise show the field value/contents.  So I'm trying to alter an existing field in the middle - not add a new field to the end.

thanks
0
 
LVL 17

Expert Comment

by:nepaluz
ID: 37031855
Ahh! Now I understand. Just use the cell template to convert the cell to buttoncells AFTER you populate , aka
dgvQueue.DataSource = dt
Me.dgvQueue.Columns("TrimCat").CellTemplate = New DataGridViewButtonCell

Open in new window

0
VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

 
LVL 17

Expert Comment

by:nepaluz
ID: 37031866
and the extra mile would be:
Me.dgvQueue.Columns("TrimCat").CellTemplate = New DataGridViewButtonCell With {.UseColumnTextForButtonValue = True}

Open in new window

0
 

Author Comment

by:sqdperu
ID: 37032543
Thanks for the help, but it does not like the "{.UseColumnTextForButtonValue = True} " at the end.  Has a blue squiggle line under it and tooltip says "end of statement expected".  So I took it off and ran it.  Then in run-time it throws an error on the line you gave me as "Value provided for CellTemplate must be of type System.Windows.Forms.DataGridViewTextBoxCell or derive from it.".

Thanks
0
 
LVL 17

Expert Comment

by:nepaluz
ID: 37032636
the "squiggle" (you called it that!) problem is because the code I suggested is .NET 4.0, here's code for previous versions. As per before, add this AFTER you populate your datagridview.
Dim c2 As DataGridViewButtonCell = New DataGridViewButtonCell
c2.UseColumnTextForButtonValue = True
Me.dgvQueue.Columns("TrimCat").CellTemplate = c2

Open in new window

0
 

Author Comment

by:sqdperu
ID: 37032800
Well, it's trying.  However, after it shows the grid (no button on column though) it errors on line "Me.dgvQueue.Columns("TrimCat").CellTemplate = c2" with error "Value provided for CellTemplate must be of type System.Windows.Forms.DataGridViewTextBoxCell or derive from it."

It just doesn't like making it a button.  I was hoping this would work, something simple.  But maybe there is another way to do this.  I don't know.

thanks
0
 

Accepted Solution

by:
sqdperu earned 0 total points
ID: 37033334
nepaluz,
Thanks for the effort.  I got a tip from antoher forum where I posed the question.  They had me look here:
http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridview.autogeneratecolumns.aspx

Which wasn't real easy to follow as the example was not using a DataTable.  With the rest of their advice "all you need to do is add the columns at design time, set autogeneratecolumns = false, then for each column, set it's datapropertyname before binding your datasource" I was able to figure it out.

So bascially using my example above, all I had to do was add the following code to my Form_Load:

Form_Load
        c1 = New DataGridViewTextBoxColumn()
        c1.Name = "Que##"
        c1.DataPropertyName = "Que#"
        Me.dgvQueue.Columns.Add(c1)
        c2 =  New DataGridViewButtonColumn()
        c2.Name = "TrimCat"
        c2.Text = "Click Here"
        c2.HeaderText = "Status-btn"
        c2.UseColumnTextForButtonValue = True
        c2.DataPropertyName = "TrimCat#"
        Me.dgvQueue.Columns.Add(c2)
        c3 = New DataGridViewTextBoxColumn()
        c3.Name = "Lock"
        c3.DataPropertyName = "Lockside"
        Me.dgvQueue.Columns.Add(c3)
        dgvQueue.AutoGenerateColumns = False
End Sub

0
 
LVL 17

Expert Comment

by:nepaluz
ID: 37033581
Setting the autogeneratecolumns value to false seems to have done it then. I was pondering suggesting not setting the datatype to string when setting up the datatable, but wanted to test it out for its effectiveness before (just could not get myself to fire up Vusual Studio though!). Anyhow, good that you solved your problem.
0
 

Author Closing Comment

by:sqdperu
ID: 37061235
It works for my situation.  Hope it may help others.
0

Featured Post

Efficient way to get backups off site to Azure

This user guide provides instructions on how to deploy and configure both a StoneFly Scale Out NAS Enterprise Cloud Drive virtual machine and Veeam Cloud Connect in the Microsoft Azure Cloud.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Parsing a CSV file is a task that we are confronted with regularly, and although there are a vast number of means to do this, as a newbie, the field can be confusing and the tools can seem complex. A simple solution to parsing a customized CSV fi…
Wouldn’t it be nice if you could test whether an element is contained in an array by using a Contains method just like the one available on List objects? Wouldn’t it be good if you could write code like this? (CODE) In .NET 3.5, this is possible…
this video summaries big data hadoop online training demo (http://onlineitguru.com/big-data-hadoop-online-training-placement.html) , and covers basics in big data hadoop .
This video shows how to quickly and easily deploy an email signature for all users in Office 365 and prevent it from being added to replies and forwards. (the resulting signature is applied on the server level in Exchange Online) The email signat…
Suggested Courses
Course of the Month17 days, 11 hours left to enroll

830 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question