Help with changing headertext color of DataGridView if value found using VB.NET

vcharles
vcharles used Ask the Experts™
on
Hi,

How do you loop through a DataGrid View and change all columnheaders text color if a value is found (i.e. textboxt.text = BEL) in their cell?

Thanks,

Victor
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®

Author

Commented:
Hi again,

Is it also possible to set the condition for multiple values (i.e.Textbox.Text = 'BEL', 'USA')

Victor
try this , will change header style for all columns.

Protected Sub GridView1_RowDataBound(sender As Object, e As GridViewRowEventArgs)  

   If e.Row.RowType = DataControlRowType.DataRow Then

         If e.Row.Cells(2).Text ='BEL' OR e.Row.Cells(2).Text =''USA''   Then

         GridView1.HeaderStyle.ForeColor = Color.OrangeRed

        End If

     End If

7 End Sub
Top Expert 2015
Commented:
Pratima code is for a GridView, in a web application.

In a DataGridView, the following will do the trick:

	Sub CheckForValues()

		For row As Integer = 0 To DataGridView1.Rows.Count - 1
			For col As Integer = 0 To DataGridView1.Columns.Count - 1
				If CStr(DataGridView1.Item(col, row).Value) = "BEL" Or CStr(DataGridView1.Item(col, row).Value) = "USA" Then
					DataGridView1.ColumnHeadersDefaultCellStyle.BackColor = Color.Red
					Exit Sub
				End If
			Next
		Next

	End Sub

Open in new window

Learn SQL Server Core 2016

This course will introduce you to SQL Server Core 2016, as well as teach you about SSMS, data tools, installation, server configuration, using Management Studio, and writing and executing queries.

Author

Commented:
Hi,

I tried the code below, but all the colomn hearders are affected, how do I only change the colors of the columns which contains the values?

Sub CheckForValues()

		For row As Integer = 0 To DataGridView1.Rows.Count - 1
			For col As Integer = 0 To DataGridView1.Columns.Count - 1
				If CStr(DataGridView1.Item(col, row).Value) = "BEL" Or CStr(DataGridView1.Item(col, row).Value) = "USA" Then
					DataGridView1.ColumnHeadersDefaultCellStyle.BackColor = Color.Red
					Exit Sub
				End If
			Next
		Next

	End Sub

Open in new window


Thanks,

Victor
Most Valuable Expert 2012
Top Expert 2014

Commented:
Change line 6 to

DataGridView1.Columns(Col).HeaderCell.Style.BackColor = Color.Red
Top Expert 2015

Commented:
Sorry for the bad line. You just asked how to "change all columnheaders ", so I gave you the code for ALL column heaners.

Author

Commented:
Thank You, will get back to you in a few minutes.

Author

Commented:
It works.

Thank You.

Victor

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial