Solved

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

Posted on 2004-08-29
11
844 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
[X]
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
11 Comments
 
LVL 10

Expert Comment

by:prakash_prk
ID: 11928834

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

regards
prakash
0
 

Author Comment

by:LMGONCA
ID: 11929372
Hi.

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

Backcolor.

Regards.
LMG
0
 
LVL 10

Expert Comment

by:123654789987
ID: 11929391
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
Online Training Solution

Drastically shorten your training time with WalkMe's advanced online training solution that Guides your trainees to action. Forget about retraining and skyrocket knowledge retention rates.

 
LVL 10

Expert Comment

by:prakash_prk
ID: 11929601

Hi LMGONCA
refer the link

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

Question :  5.14

regards
prakash
0
 

Author Comment

by:LMGONCA
ID: 11929694
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
ID: 11930268
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
ID: 12083331
it is use for changing row color
 Me.DataGrid1.AlternatingBackColor = Color.LightBlue
0
 

Expert Comment

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

Featured Post

Online Training Solution

Drastically shorten your training time with WalkMe's advanced online training solution that Guides your trainees to action. Forget about retraining and skyrocket knowledge retention rates.

Question has a verified solution.

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

Calculating holidays and working days is a function that is often needed yet it is not one found within the Framework. This article presents one approach to building a working-day calculator for use in .NET.
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…
There's a multitude of different network monitoring solutions out there, and you're probably wondering what makes NetCrunch so special. It's completely agentless, but does let you create an agent, if you desire. It offers powerful scalability …
In this video you will find out how to export Office 365 mailboxes using the built in eDiscovery tool. Bear in mind that although this method might be useful in some cases, using PST files as Office 365 backup is troublesome in a long run (more on t…

627 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