Solved

Datagridview control last row back color red vb.net

Posted on 2016-11-30
4
15 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 39

Expert Comment

by:Kyle Abrahams
Comment Utility
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
Comment Utility
I've always used DefaultCellStyle, just like you did in the first code snippet.

You might also try the DataBindingComplete event.
0
 
LVL 32

Accepted Solution

by:
it_saige earned 500 total points
Comment Utility
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
Comment Utility
Thank you.
0

Featured Post

IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

Microsoft Reports are based on a report definition, which is an XML file that describes data and layout for the report, with a different extension. You can create a client-side report definition language (*.rdlc) file with Visual Studio, and build g…
It’s quite interesting for me as I worked with Excel using vb.net for some time. Here are some topics which I know want to share with others whom this might help. First of all if you are working with Excel then you need to Download the Following …
In this seventh video of the Xpdf series, we discuss and demonstrate the PDFfonts utility, which lists all the fonts used in a PDF file. It does this via a command line interface, making it suitable for use in programs, scripts, batch files — any pl…
This video shows how to remove a single email address from the Outlook 2010 Auto Suggestion memory. NOTE: For Outlook 2016 and 2013 perform the exact same steps. Open a new email: Click the New email button in Outlook. Start typing the address: …

743 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

16 Experts available now in Live!

Get 1:1 Help Now