how to make display status of checkbox checked in datagridview

Locked how to make display status of checkbox checked in datagridview

  • Sunday, April 29, 2012 4:25 AM
     
      Has Code

    Dear Forum,

    I have a datagridview with 3 columns 1-ID, 2-CategoriesName, and 3-Select

    I want to make the status with label status that can be show to users the numbers of categories were selected  by checkboxes (It's mean that count or sum the rows been checked by checkbox on each row) and this is the code i got from searching true or false because it did not work so please need helping from forum to steering me in the right direction.

    Private Sub dataGridView1_CellClick(sender As Object, e As DataGridViewCellEventArgs)
    
    
    	Dim dgv1 As New DataGridView()
    
    	Dim idstring As String = dataGridView1.SelectedRows(0).Cells("Select").Value.ToString()
    
    	Dim parseid As Integer = Int32.Parse(idstring)
    
    	Dim id As Integer = Convert.ToInt32(parseid)
    
    	Dim dataContext = New LINQTESTDataContext()
    
    	Dim check As COPPER = dataContext.COPPERs.SingleOrDefault(Function(c) c.COIN_ID = id)
    
    
    	If CBool(Me.dataGridView1.Rows(0).Cells(1).Value) = False Then
    
    		check.CheckBox = True
    
    
    	ElseIf CBool(Me.dataGridView1.Rows(0).Cells(1).Value) = True Then
    
    
    
    		check.CheckBox = False
    	End If
    
    
    
    	Label1.Text = idstring
    
    	dataContext.SubmitChanges()
    
    End Sub
    
    P.S Please Show how me how to make select header checkbox (Select All).

    Kind regards,

    Kalunche

All Replies

  • Sunday, April 29, 2012 2:38 PM
     
     Answered Has Code

    Here is how to show the count of checked items (rows) against the DataGridView

    Private Sub DataGridView1SelectAll_CurrentCellDirtyStateChanged(
        ByVal sender As Object,
        ByVal e As EventArgs) _
    Handles DataGridView1.CurrentCellDirtyStateChanged
        If TypeOf DataGridView1.CurrentCell Is DataGridViewCheckBoxCell Then
            DataGridView1.EndEdit()
            Label1.Text =
                (
                    From T In DataGridView1.Rows.OfType(Of DataGridViewRow)()
                    Where CBool(T.Cells("Select").Value)
                ).Count.ToString
        End If
    End Sub

    If you DataGridView DataSource was a DataTable.

    Label1.Text =
        (
            From T In CType(DataGridView1.DataSource, DataTable).AsEnumerable
            Where T.Field(Of Boolean)("Select") = True
            Select T
        ).Count.ToString

    To have a select all and deselect all the following Code Project article (in C Sharp) explains how too. If you need a VB.NET version I can upload a project to my personal site which follows the authors article. Please note there is a good deal of code involved for this option.

    This is a full example of the code listed above to try it out.

    Public Class Form1
        WithEvents bsPeople As New BindingSource
        Private Sub Form1_Load( _
            ByVal sender As System.Object, _
            ByVal e As System.EventArgs) Handles MyBase.Load
            DataGridView1.AllowUserToAddRows = False
            Dim dt = GetMockedData()
            dt.Columns.Add( _
                New DataColumn With _
                { _
                    .DataType = GetType(Boolean), .ColumnName = "Select" _
                } _
            )
            ' Position to first column is optional
            dt.Columns("Select").SetOrdinal(0)
            ' give each row a value for the injected column
            For Each row As DataRow In dt.Rows
                row("Select") = False
            Next
            dt.AcceptChanges()
            bsPeople.DataSource = dt
            DataGridView1.DataSource = dt
        End Sub
        ''' <summary>
        ''' This would be your data from your table in a database
        ''' </summary>
        ''' <returns></returns>
        ''' <remarks></remarks>
        Private Function GetMockedData() As DataTable
            Dim table As New DataTable()
            table.Columns.Add("Identifier", GetType(Integer))
            table.Columns.Add("FirstName", GetType(String))
            table.Columns.Add("LastName", GetType(String))
            table.Rows.Add(10, "John", "Smith")
            table.Rows.Add(20, "Mary", "Willson")
            table.Rows.Add(30, "Frank", "Mills")
            table.Rows.Add(40, "Amy", "Jones")
            Return table
        End Function
        Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
            Dim Items =
                (
                    From T In CType(DataGridView1.DataSource, DataTable).AsEnumerable
                    Where T.Field(Of Boolean)("Select") = True
                    Select T
                ).ToList
            If Items.Count > 0 Then
                Label1.Text = "Selected count of checked items '" & Items.Count.ToString & "'"
                Dim sb As New System.Text.StringBuilder
                sb.AppendLine("There are '" & Items.Count & "' checked")
                For Each item In Items
                    sb.AppendLine(String.Format("[{0}] [{1}] [{2}]",
                                                item("Identifier"),
                                                item("FirstName"),
                                                item("LastName")))
                Next
                MessageBox.Show(sb.ToString)
            Else
                MessageBox.Show("Nothing checked")
            End If
        End Sub
        Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
            Label1.Text =
                (
                    From T In CType(DataGridView1.DataSource, DataTable).AsEnumerable
                    Where T.Field(Of Boolean)("Select") = True
                    Select T
                ).Count.ToString
        End Sub
        Private Sub DataGridView1SelectAll_CurrentCellDirtyStateChanged(
            ByVal sender As Object,
            ByVal e As EventArgs) _
        Handles DataGridView1.CurrentCellDirtyStateChanged
            If TypeOf DataGridView1.CurrentCell Is DataGridViewCheckBoxCell Then
                DataGridView1.EndEdit()
                Label1.Text =
                    (
                        From T In DataGridView1.Rows.OfType(Of DataGridViewRow)()
                        Where CBool(T.Cells("Select").Value)
                    ).Count.ToString
            End If
        End Sub
    End Class


    KSG


  • Sunday, April 29, 2012 4:50 PM
     
     

    Dear Kevininstructor,

    Thank you very much i will follow your structure.

    Kind regards,

    Kalunche

  • Wednesday, May 02, 2012 2:48 PM
     
     

    Dear Kevininstructor,

    Your code was work very well. But in my database not fixed the name like your sample code. It's mean that i used local database.sdf So I have a datagridview with 3 columns 1-ID, 2-CategoriesName, and 3-Select(CheckAll). For column categories can be add another name of categories later on. In the form i've been seperated a two forms

    1. The first form is form Add name of categorie (i chose Details and drop on the form)  

    2. The second form is form Preview (i chose Datagrid) draged to make the preview form

    My problem is i don't know how to replace with the code underline below . For the column i can name it but for the rows can't  do it because it always update the name of categories.

     ''' <summary>
       
    ''' This would be your data from your table in a database
       
    ''' </summary>
       
    ''' <returns></returns>
       
    ''' <remarks></remarks>
       
    Private Function GetMockedData() As DataTable
           
    Dim table As New DataTable()
            table
    .Columns.Add("Identifier", GetType(Integer))
            table
    .Columns.Add("FirstName", GetType(String))
            table
    .Columns.Add("LastName", GetType(String))
            table.Rows.Add(10,
    "John", "Smith")
            table.Rows.Add(20,
    "Mary", "Willson")
            table.Rows.Add(30,
    "Frank", "Mills")
            table.Rows.Add(40,
    "Amy", "Jones")
    Return table
       
    End Function

    With kind regards,

    Kalunche


    • Edited by Kalunche Wednesday, May 02, 2012 2:51 PM
    •  
  • Wednesday, May 02, 2012 3:44 PM
     
      Has Code

    Dear Kevininstructor,

    Your code was work very well. But in my database not fixed the name like your sample code. It's mean that i used local database.sdf So I have a datagridview with 3 columns 1-ID, 2-CategoriesName, and 3-Select(CheckAll). For column categories can be add another name of categories later on. In the form i've been seperated a two forms

    1. The first form is form Add name of categorie (i chose Details and drop on the form)  

    2. The second form is form Preview (i chose Datagrid) draged to make the preview form

    My problem is i don't know how to replace with the code underline below . For the column i can name it but for the rows can't  do it because it always update the name of categories.

     ''' <summary>
       
    ''' This would be your data from your table in a database
       
    ''' </summary>
       
    ''' <returns></returns>
       
    ''' <remarks></remarks>
       
    Private Function GetMockedData() As DataTable
           
    Dim table As New DataTable()
            table
    .Columns.Add("Identifier", GetType(Integer))
            table
    .Columns.Add("FirstName", GetType(String))
            table
    .Columns.Add("LastName", GetType(String))
            table.Rows.Add(10,
    "John", "Smith")
            table.Rows.Add(20,
    "Mary", "Willson")
            table.Rows.Add(30,
    "Frank", "Mills")
            table.Rows.Add(40,
    "Amy", "Jones")
    Return table
       
    End Function

    With kind regards,

    Kalunche


    The code I presented was to load data w/o (using GetMockedData) the need for a database, you need to load the data from your database. In the example below I use a DataContext similar to what you have in your first post where by using a language extension method convert the LINQ result to a DataTable. This is what you will need, grab data from your database into a DataTable.

    Private Function GetDataFromDatabase() As DataTable
        Dim db As New DataClasses1DataContext
        Return _
            (
                From T In db.Customers
                Select New With
                       {
                           .Identifier = T.Identifier,
                           .FirstName = T.FirstName,
                           .LastName = T.LastName
                       }
            ).ToDataTable
    End Function
    Private Sub Form1_Load( _
        ByVal sender As System.Object, _
        ByVal e As System.EventArgs) Handles MyBase.Load
        DataGridView1.AllowUserToAddRows = False
        Dim dt = GetDataFromDatabase()
        dt.Columns.Add( _
            New DataColumn With _
            { _
                .DataType = GetType(Boolean), .ColumnName = "Select" _
            } _
        )
        ' Position to first column is optional
        dt.Columns("Select").SetOrdinal(0)
        ' give each row a value for the injected column
        For Each row As DataRow In dt.Rows
            row("Select") = False
        Next
        dt.AcceptChanges()
        bsPeople.DataSource = dt
        DataGridView1.DataSource = dt
    End Sub

    Language extension (place into a code module) for above.

    <System.Diagnostics.DebuggerStepThrough()> _
    <System.Runtime.CompilerServices.Extension()> _
    Public Function ToDataTable(Of T)(ByVal value As IEnumerable(Of T)) As DataTable
        Dim returnTable As New DataTable
        Dim firstRecord = value.First
        For Each pi In firstRecord.GetType.GetProperties
            returnTable.Columns.Add(pi.Name, pi.GetValue(firstRecord, Nothing).GetType)
        Next
        For Each result In value
            Dim nr = returnTable.NewRow
            For Each pi In result.GetType.GetProperties
                nr(pi.Name) = pi.GetValue(result, Nothing)
            Next
            returnTable.Rows.Add(nr)
        Next
        Return returnTable
    End Function


    KSG

  • Friday, May 04, 2012 12:22 AM
     
     

    Dear Kevininstructor,

    Based on your this time sample code i did not understand where is the code should i replace it. For Private Sub Form1_load... i did but others i don't understand where should it be. Could you please make like as posted above.

    Kind regards,

    Kalunche

  • Friday, May 04, 2012 2:37 AM
     
     

    Dear Kevininstructor,

    Based on your this time sample code i did not understand where is the code should i replace it. For Private Sub Form1_load... i did but others i don't understand where should it be. Could you please make like as posted above.

    Kind regards,

    Kalunche


    If you study the code line by line you will notice Form Load which means that is a suggested spot for the code for the first code block. The line above the second code block indicates that you are to place the code into a code module.

    KSG

  • Saturday, May 05, 2012 6:50 AM
     
     

    Dear KevininStructor,

    I tried as below it's right or wrong. It's showed me some errors like i take note as underline

        Public Function ToDataTable(Of T)(ByVal value As IEnumerable(Of T)) As DataTable
            Dim returnTable As New DataTable
            Dim firstRecord = value.First
            For Each pi In firstRecord.GetType.GetProperties
                returnTable.Columns.Add(pi.Name, pi.GetValue(firstRecord, Nothing).GetType)
            Next
            For Each result In value
                Dim nr = returnTable.NewRow
                For Each pi In result.GetType.GetProperties
                    nr(pi.Name) = pi.GetValue(result, Nothing)
                Next
                returnTable.Rows.Add(nr)
            Next
            Return returnTable
    End Function

        Private Sub FrmMain_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

            OrderDataGridView.AllowUserToAddRows = False
            Dim dt = GetDataFromDatabase()
            dt.Columns.Add(New DataColumn With {.DataType = GetType(Boolean), .ColumnName = "Select"})
            ' Position to first column is optional
            dt.Columns("Select").SetOrdinal(0)
            ' give each row a value for the injected column
            For Each row As DataRow In dt.Rows
            row("Select") = False
            Next
            dt.AcceptChanges()
            bsPeople.DataSource = dt
            OrderDataGridView.DataSource = dt

    Kind regards,

    Kalunche