I tried my best to shrink down the program to the following code. In this example, I have UK and USA as valid countries. If someone lives outside those countries, I wanna show an error message and highlight them on the gridview. For example, John and Chris are from China so they should be highlighted on the gridview. Is it possible to do that ? Please see example picture. Either just Name or the whole row can be highlighted.
Thanks a lot.
Dim dt As New DataTable
dt.Columns.Add("ID")
dt.Columns.Add("Name")
dt.Columns.Add("Country")
dt.Rows.Add("1", "John", "China")
dt.Rows.Add("2", "Harry", "USA")
dt.Rows.Add("3", "Joe", "UK")
dt.Rows.Add("4", "Emma", "UK")
dt.Rows.Add("5", "Chris", "China")
dt.Rows.Add("6", "Jenny", "UK")
Dim isValid As Boolean = True
Dim keywords() As String = {"UK", "USA"}
Dim str As String = ""
For Each x As DataRow In dt.Rows
If Not keywords.Contains(x("Country").ToString()) = True Then
isValid = False
End If
Next
If isValid = False Then
lblmessage.Text = "Some people don't live in valid countries"
End If
GridView1.DataSource = dt
GridView1.DataBind()
Is it possible to do that ?
Yes, one way is to use GridView's RowDataBound
event. Assuming you have a list of valid countries:
Private validCountries() As String = {"UK", "USA"}
Protected Sub GridView1_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs)
Select Case e.Row.RowType
Case DataControlRowType.DataRow
Dim row = DirectCast(e.Row.DataItem, DataRowView).Row
Dim country = row.Field(Of String)("Country")
' assuming you're using TemplateFields with LblName for the Name of the user '
Dim LblName = DirectCast(e.Row.FindControl("LblName"), Label)
If Not validCountries.Contains(country.ToUpper) Then
LblName.CssClass = "InvalidCountry"
End If
End Select
End Sub
If you're using BoundFields instead, you need to apply the CSS on the table cell
e.Row.Cells(1).CssClass = "InvalidCountry"