Solved

How to change the color of a datagrid row in VB.NET?

Posted on 2004-08-29
11
818 Views
Last Modified: 2007-12-19
I'm trying to change the full row color for a datagrid in VB.NET?

Can you please explain me how to do this?
0
Comment
Question by:LMGONCA
11 Comments
 
LVL 10

Expert Comment

by:prakash_prk
Comment Utility

Are you want to set single row or all rows color ? back color or fore color?

regards
prakash
0
 

Author Comment

by:LMGONCA
Comment Utility
Hi.

1 row based in some criteria in a cell of that row.

Backcolor.

Regards.
LMG
0
 
LVL 10

Expert Comment

by:123654789987
Comment Utility
After <asp:datagrid> declaration u can use

<SelectedItemStyle Font-Bold="True" ForeColor="White" BackColor="#669999"></SelectedItemStyle>
      <AlternatingItemStyle cssclass="EvenRow"></AlternatingItemStyle>
                                                                        <ItemStyle CssClass="OddRow"></ItemStyle>

In the CssClass u can have the properties of OddRow and EvenRow where u can specify the foreground color
0
 
LVL 10

Expert Comment

by:prakash_prk
Comment Utility

Hi LMGONCA
refer the link

http://www.syncfusion.com/FAQ/WinForms/FAQ_c44c.asp#Top

Question :  5.14

regards
prakash
0
6 Surprising Benefits of Threat Intelligence

All sorts of threat intelligence is available on the web. Intelligence you can learn from, and use to anticipate and prepare for future attacks.

 

Author Comment

by:LMGONCA
Comment Utility
I've went trought the syncfusion link (in fact I had been exploring the link already) but I don't see any question directly related with mine (if so can you please tell me the number?).

Regards.
LMG
0
 
LVL 27

Accepted Solution

by:
planocz earned 125 total points
Comment Utility
Here is a sample on coloring cells. You should be able to adjust it to fit your needs.

'FORM1

Option Explicit On

Imports Microsoft.VisualBasic
Imports System
Imports System.ComponentModel
Imports System.Data
Imports System.Data.Common
Imports System.Data.OleDb
Imports System.Drawing
Imports System.Windows.Forms
Public Class DataGridColor
    Inherits Form
    Private WithEvents dataGrid1 As DataGrid
    Private components As Container
    'Fields
    'Constructors
    'Events
    'Methods

    Public Sub New()
        MyBase.New()
        '
        ' Required for Windows Form Designer support
        '
        InitializeComponent()

    End Sub
    Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean)

        If disposing Then
            If (Not (components) Is Nothing) Then
                components.Dispose()
            End If
        End If
        MyBase.Dispose(disposing)

    End Sub
    Private Sub InitializeComponent()

        Me.dataGrid1 = New System.Windows.Forms.DataGrid
        CType(Me.dataGrid1, System.ComponentModel.ISupportInitialize).BeginInit()
        Me.SuspendLayout()
        '
        ' dataGrid1
        '
        Me.dataGrid1.Anchor = (((System.Windows.Forms.AnchorStyles.Top Or System.Windows.Forms.AnchorStyles.Bottom) _
                    Or System.Windows.Forms.AnchorStyles.Left) _
                    Or System.Windows.Forms.AnchorStyles.Right)
        Me.dataGrid1.DataMember = ""
        Me.dataGrid1.HeaderForeColor = System.Drawing.SystemColors.ControlText
        Me.dataGrid1.Location = New System.Drawing.Point(24, 24)
        Me.dataGrid1.Name = "dataGrid1"
        Me.dataGrid1.Size = New System.Drawing.Size(448, 280)
        Me.dataGrid1.TabIndex = 0
        '
        ' DataGridColor   Form1
        '
        Me.AutoScaleBaseSize = New System.Drawing.Size(5, 13)
        Me.ClientSize = New System.Drawing.Size(504, 341)
        Me.Controls.AddRange(New System.Windows.Forms.Control() {Me.dataGrid1})
        Me.Name = "DataGridColor"
        Me.Text = "DataGridColor"
        AddHandler Me.Load, New System.EventHandler(AddressOf Form1_Load)
        CType(Me.dataGrid1, System.ComponentModel.ISupportInitialize).EndInit()
        Me.ResumeLayout(False)

    End Sub
    <STAThread()> _
    Public Shared Sub Main()

        Application.Run(New DataGridColor)

    End Sub
    Private Sub Form1_Load(ByVal sender As Object, ByVal e As EventArgs)

        ' Set the connection and sql strings
        ' assumes your mdb file is in your root
        Dim connString As String
        connString = "Provider=Microsoft.JET.OLEDB.4.0;data source=C:\Northwind.mdb"
        Dim sqlString As String
        sqlString = "SELECT * FROM customers"
        Dim dataAdapter As OleDbDataAdapter
        dataAdapter = Nothing
        Dim _dataSet As DataSet
        _dataSet = Nothing
        ' Create a table style that will hold the new column style
        ' that we set and also tie it to our customer's table from our DB
        Try
            ' Connection object
            Dim connection As OleDbConnection
            connection = New OleDbConnection(connString)
            ' Create data adapter object
            dataAdapter = New OleDbDataAdapter(sqlString, connection)
            ' Create a dataset object and fill with data using data adapter's Fill method
            _dataSet = New DataSet
            dataAdapter.Fill(_dataSet, "customers")
            connection.Close()
        Catch ex As Exception
            MessageBox.Show(((((("Problem with DB access-" & Microsoft.VisualBasic.ChrW(10) & Microsoft.VisualBasic.ChrW(10) & "   connection: " + connString) _
                            + "" & Microsoft.VisualBasic.ChrW(13) & Microsoft.VisualBasic.ChrW(10) & Microsoft.VisualBasic.ChrW(13) & Microsoft.VisualBasic.ChrW(10) & "            query: ") _
                            + sqlString) _
                            + "" & Microsoft.VisualBasic.ChrW(13) & Microsoft.VisualBasic.ChrW(10) & Microsoft.VisualBasic.ChrW(13) & Microsoft.VisualBasic.ChrW(10) & Microsoft.VisualBasic.ChrW(13) & Microsoft.VisualBasic.ChrW(10)) _
                            + ex.ToString))
            Me.Close()
            Return
        End Try
        Dim tableStyle As DataGridTableStyle
        tableStyle = New DataGridTableStyle
        tableStyle.MappingName = "customers"
        ' since the dataset has things like field name and number of columns,
        ' we will use those to create new columnstyles for the columns in our DB table
        Dim numCols As Integer
        numCols = _dataSet.Tables("customers").Columns.Count
        Dim aColumnTextColumn As DataGridColoredTextBoxColumn
        Dim i As Integer
        i = 0

        Do While (i < numCols)
            aColumnTextColumn = New DataGridColoredTextBoxColumn
            aColumnTextColumn.HeaderText = _dataSet.Tables("customers").Columns(i).ColumnName
            aColumnTextColumn.MappingName = _dataSet.Tables("customers").Columns(i).ColumnName
            tableStyle.GridColumnStyles.Add(aColumnTextColumn)
            i = (i + 1)

        Loop
        ' make the dataGrid use our new tablestyle and bind it to our table
        dataGrid1.TableStyles.Clear()
        dataGrid1.TableStyles.Add(tableStyle)
        dataGrid1.DataSource = _dataSet.Tables("customers")

    End Sub
End Class

'CLASS

Option Explicit On

Imports Microsoft.VisualBasic
Imports System
Imports System.Drawing
Imports System.Drawing.Drawing2D
Imports System.Windows.Forms


Public Class DataGridColoredTextBoxColumn
    Inherits DataGridTextBoxColumn
    'Fields
    'Constructors
    'Events
    'Methods
    Public Sub New()
        'Warning: Implementation not found
    End Sub
    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)

        ' the idea is to conditionally set the foreBrush and/or backbrush
        ' depending upon some crireria on the cell value
        ' Here, we color anything that begins with a letter higher than 'F'
        Try
            Dim o As Object
            o = Me.GetColumnValueAtRow(source, rowNum)
            If (Not (o) Is Nothing) Then
                Dim c As Char
                c = CType(o, String).Substring(0, 1)
                If (c > "F") Then
                    backBrush = New SolidBrush(Color.Pink)
                    foreBrush = New SolidBrush(Color.White)
                End If
                'Use for numeric
                'o = CInt(o)
                'If (o <= 0) Then
                '    backBrush = New SolidBrush(Color.White)
                '    foreBrush = New SolidBrush(Color.Red)
                'End If
            End If
        Catch ex As Exception
            ' empty catch
        Finally
            ' make sure the base class gets called to do the drawing with
            ' the possibly changed brushes
            MyBase.Paint(g, bounds, source, rowNum, backBrush, foreBrush, alignToRight)
        End Try

    End Sub
End Class
0
 
LVL 2

Expert Comment

by:ahmadfuwad
Comment Utility
it is use for changing row color
 Me.DataGrid1.AlternatingBackColor = Color.LightBlue
0
 

Expert Comment

by:aosexpert
Comment Utility
the code planocz  posted colors only current cell not entire row, and this is almost same as syncfusion's example
0

Featured Post

Better Security Awareness With Threat Intelligence

See how one of the leading financial services organizations uses Recorded Future as part of a holistic threat intelligence program to promote security awareness and proactively and efficiently identify threats.

Join & Write a Comment

Suggested Solutions

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 …
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…
Illustrator's Shape Builder tool will let you combine shapes visually and interactively. This video shows the Mac version, but the tool works the same way in Windows. To follow along with this video, you can draw your own shapes or download the file…
This tutorial demonstrates a quick way of adding group price to multiple Magento products.

771 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

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now