none
DataGridViewColumn background even if it's empty RRS feed

  • Question

  • Hi,

    I haven't found an answer to this.

    How can I change the background of a column, even if the DataGridView is not in use, unbounded or without any data, something like this:

    

    And then when loading data keep the color

    Any ideas?


    G.Waters

    Thursday, December 20, 2018 10:03 PM

Answers

  • See if this is what you are after, I did not change column or row headers, still works.

    '
    ' A class project for loading data from a database
    ' (On my machine)
    '
    Imports BackEnd
    Public Class Form1
        ''' <summary>
        ''' Create an instance of the data class
        ''' (On my machine)
        ''' </summary>
        Private _Operations As New DatabaseOperations
        Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
            '
            ' Since we want to control which columns show data
            '
            DataGridView1.AutoGenerateColumns = False
            '
            ' Load the DataGridView with a DataTable
            '
            DataGridView1.DataSource = _Operations.LoadCustomers()
    
            '
            ' These columns show data from a DataTable in the line above
            ' the remaining columns are not bound
            '
            DataGridView1.Columns("Column2").DataPropertyName = "Identifier"
            DataGridView1.Columns("Column3").DataPropertyName = "CompanyName"
        End Sub
        ''' <summary>
        ''' Format the rows/columns
        ''' </summary>
        ''' <param name="sender"></param>
        ''' <param name="e"></param>
        Private Sub DataGridView1_CellFormatting(
            sender As Object, e As DataGridViewCellFormattingEventArgs) _
            Handles DataGridView1.CellFormatting
    
            If e.ColumnIndex = 2 Then
                With DataGridView1
                    If Not e.RowIndex Mod 2 = 0 AndAlso e.ColumnIndex > 3 Then
                        ' do nothing
                    Else
                        e.CellStyle.BackColor = Color.Yellow
                    End If
                End With
            End If
        End Sub
    End Class

    Note column headers indicate bound and unbound columns.

    Partial designer file for alternating row color


    Please remember to mark the replies as answers if they help and unmark them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.
    VB Forums - moderator
    profile for Karen Payne on Stack Exchange, a network of free, community-driven Q&A sites

    Friday, December 21, 2018 12:40 AM
    Moderator

All replies

  • Hi,

    I haven't found an answer to this.

    How can I change the background of a column, even if the DataGridView is not in use, unbounded or without any data, something like this:

    

    And then when loading data keep the color

    Any ideas?


    G.Waters

    Hi

    Yes, here is one idea.

    'Form1 has default blank DataGridView1
    Option Strict On
    Option Explicit On
    Public Class Form1
      Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        With DataGridView1
          .Columns.Add("Column1", "Column1")
          .Columns.Add("Column2", "Column2")
          .Columns.Add("Column3", "Column3")
          .Columns.Add("Column4", "Column4")
          .Columns.Add("Column5", "Column5")
          For i As Integer = 0 To 19
            .Rows.Add()
          Next
          .CellBorderStyle = DataGridViewCellBorderStyle.None
          .AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill
          .Columns("Column4").DefaultCellStyle.BackColor = Color.LightGreen
        End With
      End Sub
    
    End Class

    Add these if appropriate

          ' to hide column headers
          .ColumnHeadersVisible = False
    
          ' to hide row headers
          .RowHeadersVisible = False


    Regards Les, Livingston, Scotland



    • Edited by leshay Thursday, December 20, 2018 10:33 PM
    Thursday, December 20, 2018 10:29 PM
  • Hi Leshay,

    You are adding rows, it doesn't work to me because later I need to databind.

    Any other idea?


    G.Waters

    Thursday, December 20, 2018 10:35 PM
  • Hi Leshay,

    You are adding rows, it doesn't work to me because later I need to databind.

    Any other idea?


    G.Waters

    Hi

    The databinding will not effect the styles of the DataGridView, so just remove the loop which adds the rows and replace with the binding.


    Regards Les, Livingston, Scotland

    Thursday, December 20, 2018 10:46 PM
  • Hi

    Here is an example which will create and implement a DataBinding along with the styles by a Button Click.

    'Form1 has default blank DataGridView1
    ' and a Button1
    Option Strict On
    Option Explicit On
    Public Class Form1
      Dim dt As New DataTable
      Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        With dt
          .Columns.Add("C1")
          .Columns.Add("C2")
          .Columns.Add("C3")
          .Columns.Add("C4")
          .Columns.Add("C5")
          For i As Integer = 0 To 19
            .Rows.Add(i, i + 33, i / 33, i - 1, i ^ 2)
          Next
        End With
    
        With DataGridView1
          .DataSource = dt
          .DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter
          .CellBorderStyle = DataGridViewCellBorderStyle.None
          .AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill
          .Columns("C4").DefaultCellStyle.BackColor = Color.LightGreen
    
          ' to hide column headers
          .ColumnHeadersVisible = False
    
          ' to hide row headers
          .RowHeadersVisible = False
        End With
      End Sub
    End Class


    Regards Les, Livingston, Scotland

    Thursday, December 20, 2018 10:56 PM
  • It's not working, what am I doing wrong?

    Using this on load:

      With dgv
                For i As Integer = 0 To 19
                    .Rows.Add()
                Next
                .Columns("cDescApl").DefaultCellStyle.BackColor = Color.LightGreen
            End With

    Also I'm using this to format it:

     dg.EnableHeadersVisualStyles = False
            dg.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.DisableResizing
            dg.BackgroundColor = Color.FromArgb(250, 250, 250)
            dg.ColumnHeadersHeight = 30
            dg.AlternatingRowsDefaultCellStyle.BackColor = Color.FromArgb(240, 240, 240)
            dg.AlternatingRowsDefaultCellStyle.SelectionForeColor = Color.Black
            dg.RowHeadersVisible = False
            dg.RowsDefaultCellStyle.BackColor = Color.FromArgb(250, 250, 250)
            dg.RowsDefaultCellStyle.SelectionForeColor = Color.Black
            dg.RowTemplate.DefaultCellStyle.SelectionBackColor = Color.FromArgb(207, 235, 252)
            dg.RowTemplate.DefaultCellStyle.SelectionForeColor = Color.Black
            dg.RowTemplate.Height = 30
            dg.CellBorderStyle = DataGridViewCellBorderStyle.None
            dg.ColumnHeadersBorderStyle = DataGridViewHeaderBorderStyle.None
    
            dg.ColumnHeadersDefaultCellStyle.ForeColor = Color.Black
            dg.ColumnHeadersDefaultCellStyle.BackColor = Color.White
    
            dg.DefaultCellStyle.ForeColor = Color.Black
            dg.DefaultCellStyle.SelectionForeColor = Color.Black
    
            dg.AutoGenerateColumns = False


    G.Waters

    Thursday, December 20, 2018 11:08 PM
  • Hi

    Well, one thing to consider. You are setting properties multiple times with different values - not that you can't do that but you need to make sure asettinf doesn't interfere with others.

    For example, you set AlternatingRowsDefaultCellStyle.BackColor which will effect already set BackColor.

    You need to show all the code as the order of execution is important here to sort out what you are trying to do.

    Did you try out the last code I posted?


    Regards Les, Livingston, Scotland

    Thursday, December 20, 2018 11:23 PM
  • Hi Leshay,

    Yes, I tried your last code and it's not working, this is the designer:

            Me.dg.AllowUserToAddRows = False
            Me.dg.AllowUserToDeleteRows = False
            Me.dg.AllowUserToResizeRows = False
            Me.MetroStyleExtender1.SetApplyMetroTheme(Me.dg, True)
            Me.dg.BackgroundColor = System.Drawing.Color.White
            Me.dg.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D
            Me.dg.CellBorderStyle = System.Windows.Forms.DataGridViewCellBorderStyle.None
            Me.dg.ColumnHeadersBorderStyle = System.Windows.Forms.DataGridViewHeaderBorderStyle.[Single]
            DataGridViewCellStyle1.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleLeft
            DataGridViewCellStyle1.BackColor = System.Drawing.Color.WhiteSmoke
            DataGridViewCellStyle1.Font = New System.Drawing.Font("Tahoma", 8.25!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
            DataGridViewCellStyle1.ForeColor = System.Drawing.SystemColors.WindowText
            DataGridViewCellStyle1.SelectionBackColor = System.Drawing.Color.LightSteelBlue
            DataGridViewCellStyle1.SelectionForeColor = System.Drawing.SystemColors.HighlightText
            DataGridViewCellStyle1.WrapMode = System.Windows.Forms.DataGridViewTriState.[True]
            Me.dg.ColumnHeadersDefaultCellStyle = DataGridViewCellStyle1
            Me.dg.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize
            Me.dg.Columns.AddRange(New System.Windows.Forms.DataGridViewColumn() {Me.img, Me.imgedi, Me.clave, Me.desc, Me.um, Me.cCantV, Me.cPreUniV, Me.cCantDvto, Me.cDescApl, Me.cIdPartida})
            Me.dg.Cursor = System.Windows.Forms.Cursors.Hand
            DataGridViewCellStyle9.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleLeft
            DataGridViewCellStyle9.BackColor = System.Drawing.SystemColors.Window
            DataGridViewCellStyle9.Font = New System.Drawing.Font("Tahoma", 8.25!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
            DataGridViewCellStyle9.ForeColor = System.Drawing.SystemColors.ControlText
            DataGridViewCellStyle9.SelectionBackColor = System.Drawing.SystemColors.Highlight
            DataGridViewCellStyle9.SelectionForeColor = System.Drawing.Color.Black
            DataGridViewCellStyle9.WrapMode = System.Windows.Forms.DataGridViewTriState.[False]
            Me.dg.DefaultCellStyle = DataGridViewCellStyle9
            Me.dg.EditMode = System.Windows.Forms.DataGridViewEditMode.EditOnEnter
            Me.dg.Location = New System.Drawing.Point(11, 123)
            Me.dg.Margin = New System.Windows.Forms.Padding(2, 4, 2, 4)
            Me.dg.Name = "dg"
            DataGridViewCellStyle10.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleLeft
            DataGridViewCellStyle10.BackColor = System.Drawing.SystemColors.Control
            DataGridViewCellStyle10.Font = New System.Drawing.Font("Tahoma", 8.25!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
            DataGridViewCellStyle10.ForeColor = System.Drawing.SystemColors.WindowText
            DataGridViewCellStyle10.SelectionBackColor = System.Drawing.Color.LightSteelBlue
            DataGridViewCellStyle10.SelectionForeColor = System.Drawing.SystemColors.HighlightText
            DataGridViewCellStyle10.WrapMode = System.Windows.Forms.DataGridViewTriState.[True]
            Me.dg.RowHeadersDefaultCellStyle = DataGridViewCellStyle10
            Me.dg.RowHeadersVisible = False
            Me.dg.RowHeadersWidth = 24
            DataGridViewCellStyle11.BackColor = System.Drawing.Color.White
            DataGridViewCellStyle11.ForeColor = System.Drawing.Color.Black
            DataGridViewCellStyle11.SelectionForeColor = System.Drawing.Color.Black
            Me.dg.RowsDefaultCellStyle = DataGridViewCellStyle11
            Me.dg.RowTemplate.Height = 28
            Me.dg.Size = New System.Drawing.Size(1087, 303)
            Me.dg.TabIndex = 328


    G.Waters

    Friday, December 21, 2018 12:00 AM
  • Hi Leshay,

    Yes, I tried your last code and it's not working, this is the designer:



    G.Waters

    Hi

    The code I posted DOES work OK.

    If it doesn't work for you then you must have changed something.

    Try it as a new test project. Add a default DGV and a default Button1. Copy/replace all the code with the code I posted and see if that works. It does here.


    Regards Les, Livingston, Scotland


    • Edited by leshay Friday, December 21, 2018 12:20 AM
    Friday, December 21, 2018 12:20 AM
  • See if this is what you are after, I did not change column or row headers, still works.

    '
    ' A class project for loading data from a database
    ' (On my machine)
    '
    Imports BackEnd
    Public Class Form1
        ''' <summary>
        ''' Create an instance of the data class
        ''' (On my machine)
        ''' </summary>
        Private _Operations As New DatabaseOperations
        Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
            '
            ' Since we want to control which columns show data
            '
            DataGridView1.AutoGenerateColumns = False
            '
            ' Load the DataGridView with a DataTable
            '
            DataGridView1.DataSource = _Operations.LoadCustomers()
    
            '
            ' These columns show data from a DataTable in the line above
            ' the remaining columns are not bound
            '
            DataGridView1.Columns("Column2").DataPropertyName = "Identifier"
            DataGridView1.Columns("Column3").DataPropertyName = "CompanyName"
        End Sub
        ''' <summary>
        ''' Format the rows/columns
        ''' </summary>
        ''' <param name="sender"></param>
        ''' <param name="e"></param>
        Private Sub DataGridView1_CellFormatting(
            sender As Object, e As DataGridViewCellFormattingEventArgs) _
            Handles DataGridView1.CellFormatting
    
            If e.ColumnIndex = 2 Then
                With DataGridView1
                    If Not e.RowIndex Mod 2 = 0 AndAlso e.ColumnIndex > 3 Then
                        ' do nothing
                    Else
                        e.CellStyle.BackColor = Color.Yellow
                    End If
                End With
            End If
        End Sub
    End Class

    Note column headers indicate bound and unbound columns.

    Partial designer file for alternating row color


    Please remember to mark the replies as answers if they help and unmark them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.
    VB Forums - moderator
    profile for Karen Payne on Stack Exchange, a network of free, community-driven Q&A sites

    Friday, December 21, 2018 12:40 AM
    Moderator
  • Thank you both !!!


    G.Waters

    Friday, December 21, 2018 5:03 PM