Solved

Setting a CheckBox Column to True in a DataGridView?

Posted on 2014-01-08
21
461 Views
Last Modified: 2014-01-14
I have a DataGridView that has 4 columns. The first column is defined as a CheckBoxCell. This DGV and it's columns are created in design mode. My problem is that when I add a row of data to the Grid, the 1st column, which is the checkbox doesn't show as a CheckBox Column rather just as a TextBoxCell. Below is my code:

    Private Sub AddShuntValueToGrid()
        Try
            Dim rowCnt As Integer = 0

            dgvShunts.Rows.Add()
            rowCnt = dgvShunts.RowCount

            dgvShunts.Rows(rowCnt - 1).Cells(0).Value = True
            dgvShunts.Rows(rowCnt - 1).Cells(1).Value = cmbShuntValues.Text & "K"
            dgvShunts.Rows(rowCnt - 1).Cells(2).Value = cmbShuntConnections.Text
            dgvShunts.Rows(rowCnt - 1).Cells(3).Value = String.Empty

            dgvShunts.Rows(rowCnt - 1).Cells(3).ReadOnly = False
            dgvShunts.CurrentCell = dgvShunts(3, rowCnt - 1)

        Catch ex As Exception
            EH.strRetVal = "frmCalibration_SizeChanged() - " & ex.Message & "...Contact Engineering!" & "~E"
        End Try

        EH.ProcessMessages(Me, sbr, EH.strRetVal)
    End Sub

Open in new window

Screenshot.jpg
0
Comment
Question by:BlakeMcKenna
  • 10
  • 6
  • 5
21 Comments
 
LVL 13

Expert Comment

by:Jesus Rodriguez
Comment Utility
uhhmmm. You add the row directly to the grid and not to the data that prepopulated it the grid?? Whisch one is the Datasource of the Grid??
0
 

Author Comment

by:BlakeMcKenna
Comment Utility
There is no datasource. The rows are added manually. The dgv's initial state is that there are NO rows.
0
 
LVL 13

Expert Comment

by:Jesus Rodriguez
Comment Utility
My Suggestion is that you create a Public Dataset with this 4 column and then binded to the grid because if not every time that you add a row you need to repaint the grid and specify that the Cell(0) will be a check box..the code will be like this more or less

Public DGSource as New Datatable()

'On The Load for the form
        Dim C0 As New DataColumn
        With C0
            .DataType = GetType(System.Boolean)
            .ColumnName = "CHK"
        End With
        Dim C1 As New DataColumn
        With C1
            .DataType = GetType(System.String)
            .ColumnName = "K Values"
        End With
        Dim C2 As New DataColumn
        With C2
            .DataType = GetType(System.String)
            .ColumnName = "K Conection"
        End With
        Dim C3 As New DataColumn
        With C3
            .DataType = GetType(System.String)
            .ColumnName = "K Other Values"
        End With

        dgvShunts.DataSource = DGSource
        dgvShunts.DataBind()


'On Your procedure
    Private Sub AddShuntValueToGrid()
        Try
       Dim RW As DataRow = DGSource.NewRow
        With RW
            .Item(0) = True
            .Item(1) = cmbShuntValues.Text & "K"
            .Item(2) = cmbShuntConnections.Text
            .Item(3) = Strings.Empty
        End With
        DGSource.Row.Add(RW)
        dgvShunts.DataSource=Nothing
        dgvShunts.DataSource = DGSource
        dgvShunts.DataBind()
   Catch ex As Exception
            EH.strRetVal = "frmCalibration_SizeChanged() - " & ex.Message & "...Contact Engineering!" & "~E"
        End Try
        EH.ProcessMessages(Me, sbr, EH.strRetVal)

Open in new window

0
 

Author Comment

by:BlakeMcKenna
Comment Utility
DataBind() doesn't work. I guess I should have specified that this is a Windows App and not a Web App. With that in mind, is there an easier way to do this. The purpose of this Grid is very simple and very little functionality. Just wondering?

Thanks,
0
 
LVL 13

Expert Comment

by:Jesus Rodriguez
Comment Utility
Will be Refresh then instead of databind()
0
 
LVL 40

Expert Comment

by:Jacques Bourgeois (James Burger)
Comment Utility
The first column is defined as a CheckBoxCell

Is this a typo? How do you define that the column should be a CheckBox?

In order to have a CheckBoxCell in the new rows, you need to define the column as a DataGridViewColumn, not a CheckBoxCell.
0
 
LVL 13

Expert Comment

by:Jesus Rodriguez
Comment Utility
Also will be more efficient to bind to a dataset that to repaint every time that you has to add a row

Look at this example here how they do it
http://www.dotnetspider.com/resources/43689-How-create-check-box-column-datagridview.aspx

Or Still double check the Declaration of the column and be sure that will be something like


Dim doWork As New DataGridViewCheckBoxColumn()
doWork.HeaderText = "CHK"
doWork.FalseValue = "0"
doWork.TrueValue = "1"
dataGridView1.Columns.Insert(0, doWork)
0
 

Author Comment

by:BlakeMcKenna
Comment Utility
Here is what I need to happen.

I want a dgv that is created with columns, the first column being a checkbox column. I've done this in the designer already but it doesn't matter, code or designer.

I want to dynamically add a row of data to the grid with the checkbox column defaulting to checked.

The only problem that I'm having right now is that I've created the dgv in designer mode. However, when I add a row of data to the datatable, it creates 2 sets of columns, which makes sense...but I only want one set of columns in the grid.
0
 
LVL 40

Expert Comment

by:Jacques Bourgeois (James Burger)
Comment Utility
I do not concur with the first line in the last message from Jesus

First of all, a DataSet is overkill when you need to fill only one grid. The role of a DataSet is to maintain relations betweeen many DataTable objects. If you have only one set of value, a DataTable is sufficient.

An a DataTable is useless if you do not really use its functions that are similar to what you do with a table in a database. It will just add useless overhead, which might lower performance if you have a lot of data.

Creating a simple class and using it in a collection takes less code than creating a DataTable and takes up less resources. Databinding works with collections, so it would work with your class if that is the way you eventually decide to go.
Public Class Shunt
   Public Property Check As Boolean
   Public Property Values As String
   ...  
End Class

Dim shunts As New Collection.Generic.List(Of Shunt)
Dim shunt As Shunt
shunt=New Shunt
shunt.Check=True
shunt.Values="whathever is True"
shunts.add(shunt)
shunt=New Shunt
shunt.Check=False
shunt.Values="whatherver is False"
shunts.add(shunt)

yourGrid.DataSource=shunts

Open in new window

But databinding does only one thing: it requires less code to fill the grid and update the data in the collection. To do that, it also brings it's own overhead and takes control of a few things, which might not be what you want.

Filling the grid as you do is thus a good way to go if you are ready to write a little more code to have more control over what happens, or if you simply need to display information in a grid without using all the resources of a container for your data.

Dataset, DataTable, Collection. They all have their use. But if your only need is to display data on the grid and you already have something that works, keep it that way.
0
 
LVL 40

Expert Comment

by:Jacques Bourgeois (James Burger)
Comment Utility
What do you mean by "2 sets of columns" and "it makes sense"? I do not see how you can have 2 sets of column when you add one row.

If you what a column to default to something, you need to react to the RowsAdded event:

Private Sub DataGridView1_RowsAdded(sender As Object, e As DataGridViewRowsAddedEventArgs) Handles DataGridView1.RowsAdded
            DataGridView1(<YourColumnIndex>, e.RowIndex).Value = True
      End Sub
0
How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

 

Author Comment

by:BlakeMcKenna
Comment Utility
James,

When I said it created 2 columns of exact columns, I should have said it just duplicated them. In the grid, the columns showed up as I had created them in the designer. But, when I added a new row to the DataTable, it essentially duplicated the columns, seeing as how the DataTable had to have the same number of columns that the Grid has. Hope that makes sense!
0
 
LVL 40

Expert Comment

by:Jacques Bourgeois (James Burger)
Comment Utility
Nope, that does not make sense, but since English is not my first language, I might be too dum to understand.

Can you send one or two screenshots so that I can understand what happens
0
 
LVL 13

Expert Comment

by:Jesus Rodriguez
Comment Utility
Check the Autogenerate COlumns on your property
0
 

Author Comment

by:BlakeMcKenna
Comment Utility
James,

I had already set the AutoGenerateColumns to False before you mentioned it and that did make a difference. I have attached a new screenshot. Below is all the code pertaining to this scenario.

    Private tblShunts As New DataTable
    '
    '
    '
    Private Sub Form1_Load()
        CreateShuntGrid()
        .
        .
        .
    End Sub
    '
    '
    '
    Private Sub CreateShuntGrid()
        Try
            tblShunts.Columns.Add("printed")
            tblShunts.Columns.Add("shunt")
            tblShunts.Columns.Add("conx")
            tblShunts.Columns.Add("output")

            dgvShunts.AutoGenerateColumns = False

        Catch ex As Exception
            EH.strRetVal = "CreateShuntGrid() - " & ex.Message & "...Contact Engineering!" & "~E"
        End Try
    End Sub
    '
    '
    '
    Private Sub AddShuntValueToGrid()
        Try
            Dim row As DataRow = tblShunts.NewRow
            Dim rowCnt As Integer = 0

            With row
                .Item(0) = True
                .Item(1) = cmbShuntValues.Text & "K"
                .Item(2) = cmbShuntConnections.Text
                .Item(3) = String.Empty
            End With

            tblShunts.Rows.Add(row)

            dgvShunts.DataSource = Nothing
            dgvShunts.DataSource = tblShunts

            rowCnt = dgvShunts.RowCount
            dgvShunts.Rows(rowCnt - 1).Cells(3).ReadOnly = False
            dgvShunts.CurrentCell = dgvShunts(3, rowCnt - 1)

        Catch ex As Exception
            EH.strRetVal = "frmCalibration_SizeChanged() - " & ex.Message & "...Contact Engineering!" & "~E"
        End Try

        EH.ProcessMessages(Me, sbr, EH.strRetVal)
    End Sub
    '
    '
    '
    Private Sub cmbShuntValues_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cmbShuntValues.SelectedIndexChanged
        Try
            If Not blnLoading Then
                If cmbShuntValues.Text.Length > 0 Then
                    AddShuntValueToGrid()
                End If
            End If

        Catch ex As Exception
            EH.strRetVal = "cmbShuntValues_SelectedIndexChanged() - " & ex.Message & "...Contact Engineering!" & "~E"
        End Try

        EH.ProcessMessages(Me, sbr, EH.strRetVal)
    End Sub

Open in new window

Screenshot.jpg
0
 
LVL 40

Expert Comment

by:Jacques Bourgeois (James Burger)
Comment Utility
Why do you use a DataGridView when it appears that you will never show more than one row?

And why the fuss with the DataTable?

There is evidently something I do not graps there.
0
 

Author Comment

by:BlakeMcKenna
Comment Utility
In a real situation, it is conceivable that more than 1 row could exist in the dgv. As far as the datatable goes...I'm only going with what Jesus Rodriguez suggested. I think there is an easier way to accomplish what I'm trying to do...just not sure what it is!
0
 
LVL 13

Expert Comment

by:Jesus Rodriguez
Comment Utility
Remember to Set the column types on this code


 Private Sub CreateShuntGrid()
        Try
         Dim Printed As New DataGridViewCheckBoxColumn()
         Printed.HeaderText = "Printed"
         Printed.FalseValue = "0"
         Printed.TrueValue = "1"
         tblShunts.Columns.Add(printed)

            tblShunts.Columns.Add("shunt")
            tblShunts.Columns.Add("conx")
            tblShunts.Columns.Add("output")

            dgvShunts.AutoGenerateColumns = False

        Catch ex As Exception
            EH.strRetVal = "CreateShuntGrid() - " & ex.Message & "...Contact Engineering!" & "~E"
        End Try
    End Sub
0
 

Author Comment

by:BlakeMcKenna
Comment Utility
I'm abandoning this approach because I am not having any luck with this.
0
 

Author Comment

by:BlakeMcKenna
Comment Utility
I refer back to my original post. Why isn't my checkbox showing up? Below is the code where I add a row to the dgv. I have created the columns in the designer.

    Private Sub AddShuntValueToGrid()
        Try
            Dim rowCnt As Integer = 0

            EH.strRetVal = ""

            dgvShunts.Rows.Add()
            rowCnt = dgvShunts.RowCount

            dgvShunts.Rows(rowCnt - 1).Cells(0).Value = True
            dgvShunts.Rows(rowCnt - 1).Cells(1).Value = cmbShuntValues.Text & "K"
            dgvShunts.Rows(rowCnt - 1).Cells(2).Value = cmbShuntConnections.Text
            dgvShunts.Rows(rowCnt - 1).Cells(3).Value = String.Empty

            dgvShunts.CurrentCell = dgvShunts(3, rowCnt - 1)
            dgvShunts.Focus()

        Catch ex As Exception
            EH.strRetVal = "AddShuntValueToGrid() - " & ex.Message & "...Contact Engineering!" & "~E"
        End Try

        EH.ProcessMessages(Me, sbr, EH.strRetVal)
    End Sub

Open in new window

0
 

Accepted Solution

by:
BlakeMcKenna earned 0 total points
Comment Utility
I figured out my problem. I needed to increase the row height from 17 to 18 and that made the checkbox show up. So...lesson here is that whenever your using a checkbox in a DataGridView, the row height needs to be at least 18.
0
 

Author Closing Comment

by:BlakeMcKenna
Comment Utility
I googled my issue and found a possible solution. I tried the suggested solution and it worked.
0

Featured Post

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
Help with uploading excel file 2 31
Object to array 7 26
VB.Net - Find String in Array 3 25
Find value in LINQ result ? 4 17
Article by: Kraeven
Introduction Remote Share is a simple remote sharing tool, enabling you to see, add and remove remote or local shares. The application is written in VB.NET targeting the .NET framework 2.0. The source code and the compiled programs have been in…
Introduction When many people think of the WebBrowser (http://msdn.microsoft.com/en-us/library/2te2y1x6%28v=VS.85%29.aspx) control, they immediately think of a control which allows the viewing and navigation of web pages. While this is true, it's a…
Sending a Secure fax is easy with eFax Corporate (http://www.enterprise.efax.com). First, Just open a new email message.  In the To field, type your recipient's fax number @efaxsend.com. You can even send a secure international fax — just include t…
Illustrator's Shape Builder tool will let you combine shapes visually and interactively. This video shows the Mac version, but the tool works the same way in Windows. To follow along with this video, you can draw your own shapes or download the file…

772 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

Need Help in Real-Time?

Connect with top rated Experts

11 Experts available now in Live!

Get 1:1 Help Now