Change Datgrid BackColor

Posted on 2005-02-24
Medium Priority
Last Modified: 2010-04-23
Is there a way to change the text or the back color of a specifc row in a datagrid after it was already filled and binded.


datagrid1.row(6).backcolor = red
datagrid1.row(5).textforecolor = blue

Any help would be great.

Question by:malanois
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
  • 3
  • 2
LVL 28

Assisted Solution

iboutchkine earned 1000 total points
ID: 13396002
Imports System.Drawing.Drawing2D

Public Class Form1
    Inherits System.Windows.Forms.Form

#Region " Windows Form Designer generated code "

    Public Sub New()

        'This call is required by the Windows Form Designer.

        'Add any initialization after the InitializeComponent() call

    End Sub

    'Form overrides dispose to clean up the component list.
    Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean)
        If disposing Then
            If Not (components Is Nothing) Then
            End If
        End If
    End Sub

    'Required by the Windows Form Designer
    Private components As System.ComponentModel.IContainer

    'NOTE: The following procedure is required by the Windows Form Designer
    'It can be modified using the Windows Form Designer.  
    'Do not modify it using the code editor.
    Friend WithEvents dg As System.Windows.Forms.DataGrid
    <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()
        Me.dg = New System.Windows.Forms.DataGrid
        CType(Me.dg, System.ComponentModel.ISupportInitialize).BeginInit()
        Me.dg.DataMember = ""
        Me.dg.HeaderForeColor = System.Drawing.SystemColors.ControlText
        Me.dg.Location = New System.Drawing.Point(0, 0)
        Me.dg.Name = "dg"
        Me.dg.Size = New System.Drawing.Size(532, 172)
        Me.dg.TabIndex = 0
        Me.AutoScaleBaseSize = New System.Drawing.Size(5, 13)
        Me.ClientSize = New System.Drawing.Size(584, 254)
        Me.Name = "Form1"
        Me.Text = "Form1"
        CType(Me.dg, System.ComponentModel.ISupportInitialize).EndInit()

    End Sub

#End Region

    Private ds As DataSet
    Private dt As DataTable

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Dim data_column As DataColumn

        ' Build the DataSet.
        ds = New DataSet

        ' Build the Sale table.
        dt = New DataTable("Sale")

        dt.Columns.Add("Item", GetType(String))
        dt.Columns.Add("Quantity", GetType(Integer))
        dt.Columns.Add("UnitPrice", GetType(Decimal))

        data_column = dt.Columns.Add("Total", GetType(Decimal))
        data_column.Expression = "Quantity * UnitPrice"

        ' Populate the table.
        Dim sale_data(2) As Object
        sale_data(0) = "Cookie"
        sale_data(1) = 12
        sale_data(2) = 0.25

        sale_data(0) = "Milk"
        sale_data(1) = 1
        sale_data(2) = 1.25

        sale_data(0) = "Towel"
        sale_data(1) = 4
        sale_data(2) = 5.95

        ' Attach the DataGrids to the DataTables.
        dg.DataSource = dt

        'attach table style (responcible for color)
    End Sub
    Private Sub AddCustomDataTableStyle()

        Dim ts1 As DataGridTableStyle
        ts1 = New DataGridTableStyle
        ts1.MappingName = "Sale"

        'add first column (Item)
        Dim ccItem As DataGridTextChanged.DataGridTextChangedColor
        ccItem = New DataGridTextChanged.DataGridTextChangedColor
        ccItem.MappingName = "Item"
        ccItem.HeaderText = "Item"
        ccItem.Width = 70
        AddHandler ccItem.TextBox.TextChanged, AddressOf dg_TextChanged

        'add second column(Quantity)
        Dim ccQty As DataGridTextChanged.DataGridTextChangedColor
        ccQty = New DataGridTextChanged.DataGridTextChangedColor
        ccQty.MappingName = "Quantity"
        ccQty.HeaderText = "Quantity"
        ccQty.Width = 50
        AddHandler ccQty.TextBox.TextChanged, AddressOf dg_TextChanged

        'add third column(UnitPrice)
        Dim ccPrice As DataGridTextChanged.DataGridTextChangedColor
        ccPrice = New DataGridTextChanged.DataGridTextChangedColor
        ccPrice.MappingName = "UnitPrice"
        ccPrice.HeaderText = "Price"
        ccPrice.Width = 60
        AddHandler ccPrice.TextBox.TextChanged, AddressOf dg_TextChanged

        'add calculated column(Total) - don't change color or text
        Dim c As DataGridTextBoxColumn
        c = New DataGridTextBoxColumn
        c.MappingName = "Total"
        c.HeaderText = "Total"
        c.Width = 50


        'attach tablestyle
    End Sub

    Private Sub dg_TextChanged(ByVal sender As Object, ByVal e As EventArgs)

        Dim dgcc As DataGridCell = Me.dg.CurrentCell
        Dim tb As TextBox = GetEmbeddedTextBox(dgcc.ColumnNumber)
        If Not (tb Is Nothing) Then
            Dim oldValue As String = Me.dg(dgcc).ToString()
            Dim newValue As String = tb.Text
            If newValue <> oldValue Then
                GetEmbeddedDGTextBox(dgcc.ColumnNumber).AddRow = Me.dg.CurrentRowIndex
            End If
        End If
    End Sub

    Private Function GetEmbeddedTextBox(ByVal col As Integer) As TextBox
        Dim tbc As DataGridTextBoxColumn = Me.dg.TableStyles("Sale").GridColumnStyles(col)
        If Not (tbc Is Nothing) AndAlso tbc.TextBox.Modified Then
            Return tbc.TextBox
        End If

        Return Nothing
    End Function

    Private Function GetEmbeddedDGTextBox(ByVal col As Integer) As DataGridTextChanged.DataGridTextChangedColor
        Dim tbc As DataGridTextChanged.DataGridTextChangedColor = Me.dg.TableStyles("Sale").GridColumnStyles(col)
        If Not (tbc Is Nothing) AndAlso tbc.TextBox.Modified Then
            Return tbc
        End If

        Return Nothing
    End Function

End Class

Namespace DataGridTextChanged
    Public Class DataGridTextChangedColor
        Inherits DataGridTextBoxColumn

        Public Sub New()
        End Sub

        Dim _row As New System.Collections.ArrayList

        Public Property AddRow() As Integer

            End Get
            Set(ByVal Value As Integer)
            End Set
        End Property

        Protected Overloads Overrides Sub Paint(ByVal g As Graphics, ByVal bounds As Rectangle, ByVal source As CurrencyManager, ByVal rowNum As Integer, ByVal backBrush As Brush, ByVal foreBrush As Brush, ByVal alignToRight As Boolean)

            If _row.Contains(rowNum) Then
                'color of changed cell 255, 200, 200
                backBrush = New LinearGradientBrush(bounds, Color.FromArgb(255, 200, 200), Color.FromArgb(128, 20, 20), LinearGradientMode.BackwardDiagonal)
                foreBrush = New SolidBrush(Color.White)
            End If

            MyBase.Paint(g, bounds, source, rowNum, backBrush, foreBrush, alignToRight)
        End Sub

    End Class

End Namespace


Author Comment

ID: 13396211
Alrighty Then.

Now If I can follow this it would be good.


Author Comment

ID: 13396662
OK, I have the class created.

I am trying to follow your code above.   I see that you are manually filling the datagrid, my grid is already filled.  

Using the above

how would i change the backcolor of row 3 in the grid.  From there i can figure out how to change the other specific rows.

Thank You,

Independent Software Vendors: 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!

LVL 28

Expert Comment

ID: 13396767
Check this sub
 Private Sub dg_TextChanged(ByVal sender As Object, ByVal e As EventArgs)

            If newValue <> oldValue Then
                GetEmbeddedDGTextBox(dgcc.ColumnNumber).AddRow = Me.dg.CurrentRowIndex
            End If

    End Sub

add if statement if the col# = whatever and it will work for every row but only for the specified column

Author Comment

ID: 13403258
I dont want the columns in every row to change.  I want row 2 (Or whatever row number I choose) and all columns in that row to change.  It is the opposite of this code.  I think

LVL 14

Accepted Solution

amyhxu earned 1000 total points
ID: 13409402

Featured Post

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!

Question has a verified solution.

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

This article explains how to create and use a custom WaterMark textbox class.  The custom WaterMark textbox class allows you to set the WaterMark Background Color and WaterMark text at design time.   IMAGE OF WATERMARKS STEPS Create VB …
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…
Do you want to know how to make a graph with Microsoft Access? First, create a query with the data for the chart. Then make a blank form and add a chart control. This video also shows how to change what data is displayed on the graph as well as form…
In this video, Percona Director of Solution Engineering Jon Tobin discusses the function and features of Percona Server for MongoDB. How Percona can help Percona can help you determine if Percona Server for MongoDB is the right solution for …
Suggested Courses
Course of the Month8 days, 3 hours left to enroll

765 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