Solved

Datagridview control last row back color red vb.net

Posted on 2016-11-30
4
93 Views
Last Modified: 2016-11-30
Hi all.

I would like to change the back color of the last row in my datagridview control to red. I've tried doing it in the CellFormatting event but no luck:

 Private Sub DataGridView1_CellFormatting(sender As Object, e As DataGridViewCellFormattingEventArgs) Handles DataGridView1.CellFormatting
        With DataGridView1

            If Not e.RowIndex Mod 2 = 0 AndAlso e.ColumnIndex >= 0 AndAlso e.ColumnIndex < 8 Then
                e.CellStyle.BackColor = Color.Beige
            ElseIf Not e.RowIndex Mod 2 = 0 AndAlso e.ColumnIndex = 8 Then
                e.CellStyle.BackColor = Color.MistyRose
            ElseIf Not e.RowIndex Mod 2 = 0 AndAlso e.ColumnIndex > 8 Then
                e.CellStyle.BackColor = Color.Beige
            Else
                e.CellStyle.BackColor = Color.White
            End If

DataGridView1.Rows(DataGridView1.Rows.Count - 1).DefaultCellStyle.BackColor = Color.Red

End With
    End Sub

Open in new window


I also tried adding the code to the button click event that loads the data into the datagridview but still no luck:

Private Sub btnRun_Click(sender As Object, e As EventArgs) Handles btnRun.Click
DataGridView1.DefaultCellStyle.WrapMode = DataGridViewTriState.True     'Word wrap 
        DataGridView1.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.AllCells  'Adjust the height of the rows
        DataGridView1.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter    'Center in the middle cell contents
        DataGridView1.ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter   'Center in the middle the column headers

DataGridView1.ClipboardCopyMode = DataGridViewClipboardCopyMode.EnableWithoutHeaderText

        DataGridView1.Columns(0).Width = 180
        DataGridView1.Columns(2).Width = 115
        DataGridView1.Columns(3).Width = 130
        DataGridView1.Columns(4).Width = 120
        DataGridView1.Columns(5).Width = 120

        DataGridView1.Rows(DataGridView1.Rows.Count - 1).DefaultCellStyle.Font = New Font("Arial", 12, FontStyle.Bold)
        DataGridView1.Rows(DataGridView1.Rows.Count - 1).DefaultCellStyle.BackColor = Color.Red

End Sub

Open in new window


Any idea what I can do to get this to work? Thank you in advance.
0
Comment
Question by:printmedia
[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
4 Comments
 
LVL 40

Expert Comment

by:Kyle Abrahams
ID: 41907977
don't use DefaultCellStyle use, style instead.

you can loop over all cells if you need to:
DataGridView1.Rows(DataGridView1.Rows.Count - 1).Cells(ColIndex).Style.BackColor = Color.Red

Open in new window

0
 
LVL 85
ID: 41907985
I've always used DefaultCellStyle, just like you did in the first code snippet.

You might also try the DataBindingComplete event.
0
 
LVL 34

Accepted Solution

by:
it_saige earned 500 total points
ID: 41907988
By comparing the e.RowIndex to the GetLastRow value; e.g. -

Form1.vb -
Imports System.Runtime.CompilerServices
Imports System.ComponentModel

Public Class Form1
	Private Sub OnLoad(sender As Object, e As EventArgs) Handles MyBase.Load
		DataGridView1.DataSource = (From i In Enumerable.Range(0, 25)
							   Select New With {.ID = i, .FirstName = String.Format("FirstName{0}", i), .MiddleName = String.Format("MiddleName{0}", i), .LastName = String.Format("LastName{0}", i), .BirthDate = DateTime.Now.AddYears(-(9 * i)), .Age = DateTime.Now.Year - .BirthDate.Year, .IsDrinking = .Age > 21, .IsWorking = .Age > 15 AndAlso .Age < 65, .IsRetired = .Age > 65}).ConvertToDataTable()
	End Sub

	Private Sub OnCellFormatting(sender As Object, e As DataGridViewCellFormattingEventArgs) Handles DataGridView1.CellFormatting
		If TypeOf sender Is DataGridView Then
			Dim grid = DirectCast(sender, DataGridView)
			If grid.Rows.Count > 0 Then
				If Not e.RowIndex Mod 2 = 0 AndAlso e.ColumnIndex >= 0 AndAlso e.ColumnIndex < 8 Then
					e.CellStyle.BackColor = Color.Beige
				ElseIf Not e.RowIndex Mod 2 = 0 AndAlso e.ColumnIndex = 8 Then
					e.CellStyle.BackColor = Color.MistyRose
				ElseIf Not e.RowIndex Mod 2 = 0 AndAlso e.ColumnIndex > 8 Then
					e.CellStyle.BackColor = Color.Beige
				ElseIf e.RowIndex = grid.Rows.GetLastRow(DataGridViewElementStates.None) Then
					grid.Rows(e.RowIndex).DefaultCellStyle.BackColor = Color.Red
				Else
					e.CellStyle.BackColor = Color.White
				End If
			End If
		End If
	End Sub
End Class

Module Extensions
	<Extension()> _
	Public Function ConvertToDataTable(Of T)(ByVal source As IEnumerable(Of T)) As DataTable
		Dim properties As PropertyDescriptorCollection = TypeDescriptor.GetProperties(GetType(T))
		Dim table As DataTable = New DataTable()

		For i As Integer = 0 To properties.Count - 1
			Dim [property] As PropertyDescriptor = properties(i)
			If [property].PropertyType.IsGenericType AndAlso [property].PropertyType.GetGenericTypeDefinition().Equals(GetType(Nullable)) Then
				table.Columns.Add([property].Name, [property].PropertyType.GetGenericArguments()(0))
			Else
				table.Columns.Add([property].Name, [property].PropertyType)
			End If
		Next

		Dim values(properties.Count - 1) As Object
		For Each item As T In source
			For i As Integer = 0 To properties.Count - 1
				values(i) = properties(i).GetValue(item)
			Next
			table.Rows.Add(values)
		Next

		Return table
	End Function
End Module

Open in new window

Form1.Designer.vb -
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
Partial Class Form1
	Inherits System.Windows.Forms.Form

	'Form overrides dispose to clean up the component list.
	<System.Diagnostics.DebuggerNonUserCode()> _
	Protected Overrides Sub Dispose(ByVal disposing As Boolean)
		Try
			If disposing AndAlso components IsNot Nothing Then
				components.Dispose()
			End If
		Finally
			MyBase.Dispose(disposing)
		End Try
	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.
	<System.Diagnostics.DebuggerStepThrough()> _
	Private Sub InitializeComponent()
		Me.DataGridView1 = New System.Windows.Forms.DataGridView()
		CType(Me.DataGridView1, System.ComponentModel.ISupportInitialize).BeginInit()
		Me.SuspendLayout()
		'
		'DataGridView1
		'
		Me.DataGridView1.AllowUserToAddRows = False
		Me.DataGridView1.AllowUserToDeleteRows = False
		Me.DataGridView1.AutoSizeColumnsMode = System.Windows.Forms.DataGridViewAutoSizeColumnsMode.Fill
		Me.DataGridView1.AutoSizeRowsMode = System.Windows.Forms.DataGridViewAutoSizeRowsMode.AllCells
		Me.DataGridView1.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize
		Me.DataGridView1.Dock = System.Windows.Forms.DockStyle.Fill
		Me.DataGridView1.Location = New System.Drawing.Point(0, 0)
		Me.DataGridView1.Name = "DataGridView1"
		Me.DataGridView1.ReadOnly = True
		Me.DataGridView1.RowHeadersVisible = False
		Me.DataGridView1.SelectionMode = System.Windows.Forms.DataGridViewSelectionMode.FullRowSelect
		Me.DataGridView1.Size = New System.Drawing.Size(884, 411)
		Me.DataGridView1.TabIndex = 0
		'
		'Form1
		'
		Me.AutoScaleDimensions = New System.Drawing.SizeF(6.0!, 13.0!)
		Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font
		Me.ClientSize = New System.Drawing.Size(884, 411)
		Me.Controls.Add(Me.DataGridView1)
		Me.Name = "Form1"
		Me.Text = "Form1"
		CType(Me.DataGridView1, System.ComponentModel.ISupportInitialize).EndInit()
		Me.ResumeLayout(False)

	End Sub
	Friend WithEvents DataGridView1 As System.Windows.Forms.DataGridView
End Class

Open in new window

Produces the following output -Capture.JPG
-saige-
0
 

Author Closing Comment

by:printmedia
ID: 41908021
Thank you.
0

Featured Post

Enroll in June's Course of the Month

June’s Course of the Month is now available! Experts Exchange’s Premium Members, Team Accounts, and Qualified Experts have access to a complimentary course each month as part of their membership—an extra way to sharpen your skills and increase training.

Question has a verified solution.

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

I think the Typed DataTable and Typed DataSet are very good options when working with data, but I don't like auto-generated code. First, I create an Abstract Class for my DataTables Common Code.  This class Inherits from DataTable. Also, it can …
Introduction As chip makers focus on adding processor cores over increasing clock speed, developers need to utilize the features of modern CPUs.  One of the ways we can do this is by implementing parallel algorithms in our software.   One recent…
In this video, viewers are given an introduction to using the Windows 10 Snipping Tool, how to quickly locate it when it's needed and also how make it always available with a single click of a mouse button, by pinning it to the Desktop Task Bar. Int…
Monitoring a network: why having a policy is the best policy? Michael Kulchisky, MCSE, MCSA, MCP, VTSP, VSP, CCSP outlines the enormous benefits of having a policy-based approach when monitoring medium and large networks. Software utilized in this v…

726 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