?
Solved

Datagridview control last row back color red vb.net

Posted on 2016-11-30
4
Medium Priority
?
167 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
4 Comments
 
LVL 41

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 35

Accepted Solution

by:
it_saige earned 2000 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

Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

This tutorial demonstrates one way to create an application that runs without any Forms but still has a GUI presence via an Icon in the System Tray. The magic lies in Inheriting from the ApplicationContext Class and passing that to Application.Ru…
Article by: Kraeven
Introduction Remote Share is a simple remote sharing tool, enabling you to see, add and remove remote or local shares. The application is written in VB.NET targeting the .NET framework 2.0. The source code and the compiled programs have been in…
this video summaries big data hadoop online training demo (http://onlineitguru.com/big-data-hadoop-online-training-placement.html) , and covers basics in big data hadoop .
When cloud platforms entered the scene, users and companies jumped on board to take advantage of the many benefits, like the ability to work and connect with company information from various locations. What many didn't foresee was the increased risk…
Suggested Courses
Course of the Month16 days, 20 hours left to enroll

864 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