Results 1 to 17 of 17

Thread: Change background colour for individual cell in datagridview

  1. #1

    Thread Starter
    Fanatic Member paulorton's Avatar
    Join Date
    Aug 2006
    Location
    West Wales
    Posts
    809

    Change background colour for individual cell in datagridview

    Code:
    dgv_WorkHistory.Rows(i).Cells("DateOfWork").Style.BackColor = Color.Green
    This doesn't change the background colour - what am I doing wrong here?
    Paul Orton
    VB6
    Visual Web Developer 2008 Express Edition
    Microsoft Visual Basic 2012 Express

  2. #2
    eXtreme Programmer .paul.'s Avatar
    Join Date
    May 2007
    Location
    Chelmsford UK
    Posts
    26,413

    Re: Change background colour for individual cell in datagridview

    are you sure the column is named "DateOfWork"?
    i tried it + it worked for me.

  3. #3

    Thread Starter
    Fanatic Member paulorton's Avatar
    Join Date
    Aug 2006
    Location
    West Wales
    Posts
    809

    Re: Change background colour for individual cell in datagridview

    Yes, it's definitely the right column - I can change its value with something like :
    Code:
    dgv_WorkHistory.Rows(i).Cells("DateOfWork").Value = "30/06/1971"
    but I can't change the background color of cells anywhere in the datagridview.
    Paul Orton
    VB6
    Visual Web Developer 2008 Express Edition
    Microsoft Visual Basic 2012 Express

  4. #4
    Fanatic Member
    Join Date
    Mar 2009
    Posts
    739

    Re: Change background colour for individual cell in datagridview

    Quote Originally Posted by paulorton View Post
    Yes, it's definitely the right column - I can change its value with something like :
    Code:
    dgv_WorkHistory.Rows(i).Cells("DateOfWork").Value = "30/06/1971"
    but I can't change the background color of cells anywhere in the datagridview.
    To change an individual cell you need to use .Style.BackColor

    dgv[col, row].Style.BackColor = Color.Tomato

    and to change a whole column you use .DefaultCellStyle.BackColor

    dgv.Columns[col].DefaultCellStyle.BackColor = Color.Tomato


    Sorry, this is c# syntax - I'm not sure if it's the same as vb but I'm sure you can work it out.

  5. #5

    Thread Starter
    Fanatic Member paulorton's Avatar
    Join Date
    Aug 2006
    Location
    West Wales
    Posts
    809

    Re: Change background colour for individual cell in datagridview

    I'm already using .Style.Backcolor and it's not working for some reason.
    Paul Orton
    VB6
    Visual Web Developer 2008 Express Edition
    Microsoft Visual Basic 2012 Express

  6. #6
    Fanatic Member
    Join Date
    Mar 2009
    Posts
    739

    Re: Change background colour for individual cell in datagridview

    I know in c# i have to be "using System.Drawing;" before I can use .Color otherwise it won't even build. Is VB strict or would it let you run without it ?

    Try this?

    dgv_WorkHistory.Rows(i).Cells("DateOfWork").Style.BackColor = System.Drawing.Color.Green

  7. #7

    Thread Starter
    Fanatic Member paulorton's Avatar
    Join Date
    Aug 2006
    Location
    West Wales
    Posts
    809

    Re: Change background colour for individual cell in datagridview

    Thanks for continuing to help but no, that didn't work. TBH I think the intellisense would have alerted me if I was using Color.Green wrongly.
    Paul Orton
    VB6
    Visual Web Developer 2008 Express Edition
    Microsoft Visual Basic 2012 Express

  8. #8
    Angel of Code Niya's Avatar
    Join Date
    Nov 2011
    Posts
    9,017

    Re: Change background colour for individual cell in datagridview

    Quote Originally Posted by paulorton View Post
    Code:
    dgv_WorkHistory.Rows(i).Cells("DateOfWork").Style.BackColor = Color.Green
    This doesn't change the background colour - what am I doing wrong here?
    This is right, I've tested it. Its really strange that it doesnt work for you.

    When I get super weird errors like this what I do is close the VS IDE and go to the application folder and delete the "bin" and "obj" folders. I then start the IDE again, reload the application and re-compile it.

    I think the IDE has a couple of bugs when it comes to editing code and re-running it, you get weird **** where stuff that is supposed to work doesnt.

  9. #9

    Thread Starter
    Fanatic Member paulorton's Avatar
    Join Date
    Aug 2006
    Location
    West Wales
    Posts
    809

    Re: Change background colour for individual cell in datagridview

    Did nothing, I'm afraid (assuming I did it correctly), but thanks for trying to help.

    Here's where I am now:

    Code:
                    dgv_WorkHistory.Rows(i).Cells(1).Style.BackColor = Color.Green
                    dgv_WorkHistory.Rows(i).Cells(1).Value = "30/06/1971"
    These 2 lines follow one another in my code but only the second one works. That's significant, though, because it shows at least that the first line is pointing to the correct cell.
    Paul Orton
    VB6
    Visual Web Developer 2008 Express Edition
    Microsoft Visual Basic 2012 Express

  10. #10
    Karen Payne MVP kareninstructor's Avatar
    Join Date
    Jun 2008
    Location
    Oregon
    Posts
    6,713

    Re: Change background colour for individual cell in datagridview

    Quote Originally Posted by paulorton View Post
    Code:
    dgv_WorkHistory.Rows(i).Cells("DateOfWork").Style.BackColor = Color.Green
    This doesn't change the background colour - what am I doing wrong here?
    Do you have any events such as CellFormatting for the DataGridView?

  11. #11

    Thread Starter
    Fanatic Member paulorton's Avatar
    Join Date
    Aug 2006
    Location
    West Wales
    Posts
    809

    Re: Change background colour for individual cell in datagridview

    Quote Originally Posted by kevininstructor View Post
    Do you have any events such as CellFormatting for the DataGridView?
    Nothing of any significance thus far (I think) - only this:-
    Code:
        Private Sub dgv_WorkHistory_CellBeginEdit(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellCancelEventArgs) Handles dgv_WorkHistory.CellBeginEdit
    
            Dim msg As String = String.Format("Editing Cell at ({0}, {1})", e.ColumnIndex, e.RowIndex)
            Me.Text = msg
    
        End Sub
    
        Private Sub dgv_WorkHistory_CellMouseClick(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellMouseEventArgs) Handles dgv_WorkHistory.CellMouseClick
    
            Dim msg As String = String.Format("Cell clicked on at ({0}, {1})", e.ColumnIndex, e.RowIndex)
            Me.Text = msg
    
        End Sub
    
        Private Sub dgv_WorkHistory_CellMouseEnter(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles dgv_WorkHistory.CellMouseEnter
    
            If e.RowIndex < 0 Then
                Exit Sub
            End If
    
            With dgv_WorkHistory.Rows(e.RowIndex).Cells(e.ColumnIndex)
                .ToolTipText = String.Format("Mouse over cell at ({0}, {1})", e.ColumnIndex, e.RowIndex)
            End With
    
        End Sub
        
    
        Private Sub cmdSaveChanges_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdSaveChanges.Click
    
           db_UpdateWorkHistory(WorkHistory_tablename, ds_WorkHistory)
    
        End Sub
    The code I'm having trouble with is part of the routine which displays the dgv for the very first time. Here it is:-
    Code:
    Private Sub Fill_dgv_WorkHistory(ByVal WorkHistory_tablename As String)
    
            Dim i As Integer
    
            ds_WorkHistory = db_GetWorkHistory(WorkHistory_tablename) 
    
            dgv_WorkHistory.DataSource = ds_WorkHistory.Tables(0).DefaultView
    
            dgv_WorkHistory.ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter
            dgv_WorkHistory.RowHeadersVisible = False
            dgv_WorkHistory.Columns(0).Visible = False 
            dgv_WorkHistory.Columns(2).Visible = False  
            dgv_WorkHistory.Columns(4).Visible = False  
            dgv_WorkHistory.Columns(5).Visible = False  
            dgv_WorkHistory.Columns(12).Visible = False 
            dgv_WorkHistory.Columns(13).Visible = False 
            dgv_WorkHistory.Columns(14).Visible = False 
            dgv_WorkHistory.Columns(15).Visible = False 
    
            dgv_WorkHistory.Columns(1).Width = 67  'DateOfWork
            dgv_WorkHistory.Columns(1).HeaderText = "Date"
            dgv_WorkHistory.Columns(1).ReadOnly = True
    
            dgv_WorkHistory.Columns(3).ReadOnly = True
    
            dgv_WorkHistory.Columns(6).Width = 34  'Try
            dgv_WorkHistory.Columns(6).HeaderText = "Tries"
            dgv_WorkHistory.Columns(6).ReadOnly = True
    
            dgv_WorkHistory.Columns(7).Width = 150  'TopicName
            dgv_WorkHistory.Columns(7).HeaderText = "Topic"
            dgv_WorkHistory.Columns(7).ReadOnly = True
    
            dgv_WorkHistory.Columns(8).Width = 26  'NumSheets
            dgv_WorkHistory.Columns(8).HeaderText = "Shts"
            dgv_WorkHistory.Columns(8).ReadOnly = True
    
            dgv_WorkHistory.Columns(9).Width = 25  'Errors
            dgv_WorkHistory.Columns(9).HeaderText = "X"
    
            dgv_WorkHistory.Columns(10).Width = 25  'Percentage
            dgv_WorkHistory.Columns(10).HeaderText = "%"
    
            dgv_WorkHistory.Columns(11).Width = 25  'Time
            dgv_WorkHistory.Columns(11).HeaderText = "T"
    
            cmdSaveChanges.Enabled = True
            cmdSettingComplete.Enabled = True
    
            Dim WorkDay As String
            Dim DateValue As Date
    
            Dim x As Integer
    
            For i = 0 To dgv_WorkHistory.RowCount - 1
    
                If CDate(dgv_WorkHistory.Rows(i).Cells("DateOfWork").Value) = Today Then
                    Todays_Row = i
                End If
    
                DateValue = CDate(dgv_WorkHistory.Rows(i).Cells("DateOfWork").Value)
                WorkDay = DateValue.ToString("ddd")
    
                If WorkDay = CurrentClassDay Then                
                    dgv_WorkHistory.Rows(i).Cells(1).Style.BackColor = Color.Green
                    dgv_WorkHistory.Rows(i).Cells(1).Value = "30/06/1971"
                    
                    If Todays_Row > 0 Then
                        If i >= Todays_Row And i < Todays_Row + 7 Then
                            dgv_WorkHistory.Rows(i).Cells(1).Style.BackColor = Color.Red
                        End If
                    Else
                        dgv_WorkHistory.Rows(0).Cells("DateOfWork").Style.BackColor = Color.Red
                    End If
                End If
            Next
    
        End Sub
    Paul Orton
    VB6
    Visual Web Developer 2008 Express Edition
    Microsoft Visual Basic 2012 Express

  12. #12
    Angel of Code Niya's Avatar
    Join Date
    Nov 2011
    Posts
    9,017

    Re: Change background colour for individual cell in datagridview

    It looks like that column is filled with dates loaded from a Database.
    Change:-
    vbnet Code:
    1. dgv_WorkHistory.Rows(i).Cells(1).Value = "30/06/1971"
    to something like:
    vbnet Code:
    1. dgv_WorkHistory.Rows(i).Cells(1).Value = "VERY DISTINCT VALUE"
    So you can be absolutely 200&#37; certain that you got the right cell and that the code is executing. There is no reason for that code not to work as far as I can see.
    Last edited by Niya; Jan 13th, 2012 at 01:10 PM. Reason: Minor change

  13. #13
    Karen Payne MVP kareninstructor's Avatar
    Join Date
    Jun 2008
    Location
    Oregon
    Posts
    6,713

    Re: Change background colour for individual cell in datagridview

    Have you considered then using CellFormatting event to change the desired colors?

    Try the following, see if it will work for you, requires a DataGridView on a form with the following code. A string and Date column are formatted in the CellFormat event.

    Code:
    Public Class Form2
       WithEvents bsData As New BindingSource
       Private Sub DataGridView1_CellFormatting( _
          ByVal sender As Object, _
          ByVal e As System.Windows.Forms.DataGridViewCellFormattingEventArgs) _
          Handles DataGridView1.CellFormatting
    
          If e.ColumnIndex = DataGridView1.Columns("Column2").Index Then
             If e.Value.ToString = "2" Then
                e.CellStyle.BackColor = Color.Crimson
                e.CellStyle.ForeColor = Color.White
             End If
          End If
          If e.ColumnIndex = DataGridView1.Columns("Column3").Index Then
             If CType(e.Value, DateTime).Month > Now.Month Then
                e.CellStyle.BackColor = Color.Green
                e.CellStyle.ForeColor = Color.White
             End If
          End If
       End Sub
       Private Sub Form2_Load( _
          ByVal sender As System.Object, _
          ByVal e As System.EventArgs) Handles MyBase.Load
    
          bsData.DataSource = MockData()
          DataGridView1.AllowUserToAddRows = False
          DataGridView1.DataSource = bsData
          DataGridView1.Columns("Column3").DefaultCellStyle.Format = "d"
       End Sub
       Private Function MockData() As DataTable
          Dim dt As New DataTable With {.TableName = "MyTable"}
          dt.Columns.AddRange(New DataColumn() _
             { _
                New DataColumn("Column1", GetType(System.String)), _
                New DataColumn("Column2", GetType(System.String)), _
                New DataColumn("Column3", GetType(System.DateTime)) _
             } _
          )
    
          dt.Rows.Add(New Object() {"A", "1", Now})
          dt.Rows.Add(New Object() {"B", "2", Now.AddMonths(1)})
          dt.Rows.Add(New Object() {"C", "3", Now})
          dt.Rows.Add(New Object() {"D", "2", Now.AddMonths(2)})
          dt.Rows.Add(New Object() {"E", "5", Now})
          dt.Rows.Add(New Object() {"F", "6", Now.AddMonths(3)})
    
          dt.AcceptChanges()
    
          Return dt
       End Function
    End Class

  14. #14

    Thread Starter
    Fanatic Member paulorton's Avatar
    Join Date
    Aug 2006
    Location
    West Wales
    Posts
    809

    Re: Change background colour for individual cell in datagridview

    Brilliant - that did the trick! Many thanks!

    Now the question arises : does the failure of my original code to work constitute a bug in VB.Net (given that the syntax was fine and intellisense didn't object to it) or is there an undocumented (or very well hidden) reason why VB won't allow it to work?
    Paul Orton
    VB6
    Visual Web Developer 2008 Express Edition
    Microsoft Visual Basic 2012 Express

  15. #15
    eXtreme Programmer .paul.'s Avatar
    Join Date
    May 2007
    Location
    Chelmsford UK
    Posts
    26,413

    Re: Change background colour for individual cell in datagridview

    Quote Originally Posted by paulorton View Post
    Now the question arises : does the failure of my original code to work constitute a bug in VB.Net (given that the syntax was fine and intellisense didn't object to it) or is there an undocumented (or very well hidden) reason why VB won't allow it to work?
    it's something specific to your project.
    both me + Niya tested it + it worked for us, so it must be your project

  16. #16
    New Member
    Join Date
    Jan 2012
    Posts
    1

    Re: Change background colour for individual cell in datagridview

    didn't see this option posted, so thought I'd add it ...

    vb Code:
    1. Dim QtyCell As DataGridViewCell
    2. Dim TraysCell As DataGridViewCell
    3.  
    4. For i = 0 To fdgAddProducts.EmbeddedDataGridView.RowCount - 1
    5.             days2cellsize = fdgAddProducts.EmbeddedDataGridView.Rows(i).Cells("urc_daystocellsize").Value
    6.             Dim stickDate As Date = DateAdd(DateInterval.Day, -days2cellsize, m_OrderShipDate)
    7.             If Date.Today.Date > stickDate.Date Then 'if no time to grow plant we can't sell it
    8.     'color cells of product user can't sell
    9.                 QtyCell = fdgAddProducts.EmbeddedDataGridView.Rows(i).Cells("Quantity")
    10.                 QtyCell.Style.BackColor = Color.LightGray
    11.                 TraysCell = fdgAddProducts.EmbeddedDataGridView.Rows(i).Cells("Trays")
    12.                 TraysCell.Style.BackColor = Color.LightGray
    13.             End If
    14. Next
    Last edited by gep13; Jan 24th, 2012 at 02:28 AM. Reason: Added Code Tags

  17. #17
    Karen Payne MVP kareninstructor's Avatar
    Join Date
    Jun 2008
    Location
    Oregon
    Posts
    6,713

    Re: Change background colour for individual cell in datagridview

    Quote Originally Posted by john_t View Post
    didn't see this option posted, so thought I'd add it ...

    vb Code:
    1. Dim QtyCell As DataGridViewCell
    2. Dim TraysCell As DataGridViewCell
    3.  
    4. For i = 0 To fdgAddProducts.EmbeddedDataGridView.RowCount - 1
    5.             days2cellsize = fdgAddProducts.EmbeddedDataGridView.Rows(i).Cells("urc_daystocellsize").Value
    6.             Dim stickDate As Date = DateAdd(DateInterval.Day, -days2cellsize, m_OrderShipDate)
    7.             If Date.Today.Date > stickDate.Date Then 'if no time to grow plant we can't sell it
    8.     'color cells of product user can't sell
    9.                 QtyCell = fdgAddProducts.EmbeddedDataGridView.Rows(i).Cells("Quantity")
    10.                 QtyCell.Style.BackColor = Color.LightGray
    11.                 TraysCell = fdgAddProducts.EmbeddedDataGridView.Rows(i).Cells("Trays")
    12.                 TraysCell.Style.BackColor = Color.LightGray
    13.             End If
    14. Next
    This would not handle changing formatting after a cell value changed by a user altering a cell value say by selecting a cell, press F2, change the cell value and pressing ENTER where the cell formatting event will.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width