Solved

Datagridview control last row back color red vb.net

Posted on 2016-11-30
4
37 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 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 84
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 33

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

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

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

Suggested Solutions

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…
Well, all of us have seen the multiple EXCEL.EXE's in task manager that won't die even if you call the .close, .dispose methods. Try this method to kill any excels in memory. You can copy the kill function to create a check function and replace the …
This Micro Tutorial will teach you how to censor certain areas of your screen. The example in this video will show a little boy's face being blurred. This will be demonstrated using Adobe Premiere Pro CS6.
Windows 10 is mostly good. However the one thing that annoys me is how many clicks you have to do to dial a VPN connection. You have to go to settings from the start menu, (2 clicks), Network and Internet (1 click), Click VPN (another click) then fi…

911 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

19 Experts available now in Live!

Get 1:1 Help Now