Solved

Setting a CheckBox Column to True in a DataGridView?

Posted on 2014-01-08
21
473 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 10
  • 6
  • 5
21 Comments
 
LVL 13

Expert Comment

by:Jesus Rodriguez
ID: 39765726
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
ID: 39765753
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
ID: 39765790
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
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 

Author Comment

by:BlakeMcKenna
ID: 39765814
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
ID: 39765861
Will be Refresh then instead of databind()
0
 
LVL 40
ID: 39765862
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
ID: 39765868
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
ID: 39765956
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
ID: 39766012
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
ID: 39766064
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
 

Author Comment

by:BlakeMcKenna
ID: 39766116
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
ID: 39766168
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
ID: 39766201
Check the Autogenerate COlumns on your property
0
 

Author Comment

by:BlakeMcKenna
ID: 39766266
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
ID: 39766314
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
ID: 39766380
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
ID: 39766577
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
ID: 39766630
I'm abandoning this approach because I am not having any luck with this.
0
 

Author Comment

by:BlakeMcKenna
ID: 39768266
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
ID: 39768443
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
ID: 39778764
I googled my issue and found a possible solution. I tried the suggested solution and it worked.
0

Featured Post

Instantly Create Instructional Tutorials

Contextual Guidance at the moment of need helps your employees adopt to new software or processes instantly. Boost knowledge retention and employee engagement step-by-step with one easy solution.

Question has a verified solution.

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

Microsoft Reports are based on a report definition, which is an XML file that describes data and layout for the report, with a different extension. You can create a client-side report definition language (*.rdlc) file with Visual Studio, and build g…
It was really hard time for me to get the understanding of Delegates in C#. I went through many websites and articles but I found them very clumsy. After going through those sites, I noted down the points in a easy way so here I am sharing that unde…
I've attached the XLSM Excel spreadsheet I used in the video and also text files containing the macros used below. https://filedb.experts-exchange.com/incoming/2017/03_w12/1151775/Permutations.txt https://filedb.experts-exchange.com/incoming/201…
Attackers love to prey on accounts that have privileges. Reducing privileged accounts and protecting privileged accounts therefore is paramount. Users, groups, and service accounts need to be protected to help protect the entire Active Directory …

738 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