As a general rule? You can "attempt" to write some expressions in the markup.
However, if you have quite a few conditions?
For GridView, ListView, Repeater - and most of the data "repeating" controls?
I suggest you use the row data bound event. (or item data bound event - they all work much the same).
It is quite nice for setting colors, hiding, showing, and more.
And you get the one database row during binding. So, all the code, messy formatting is in one nice clean VB routine.
So, say this simple markup:
And then our code.
We will:
Only show label 1 if ID (record pk) is <= 1
Only show lable 2 if id <=2
And for good measure, if the true/false column Active = true, then we will highlight the Hotel text box with a light blue.
So, our code is this:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not IsPostBack Then
LoadData
End If
End Sub
Sub LoadData()
Using conn As New SqlConnection(My.Settings.TEST4)
Dim strSQL As String = "SELECT * FROM tblHotelsA ORDER BY ID"
Using cmdSQL As New SqlCommand(strSQL, conn)
conn.Open()
Dim rstData As New DataTable
rstData.Load(cmdSQL.ExecuteReader)
Repeater1.DataSource = rstData
Repeater1.DataBind()
End Using
End Using
End Sub
Protected Sub Repeater1_ItemDataBound(sender As Object, e As RepeaterItemEventArgs) Handles Repeater1.ItemDataBound
If e.Item.ItemType = ListItemType.Item Or
e.Item.ItemType = ListItemType.AlternatingItem Then
Dim OneRow As DataRow = e.Item.DataItem.Row ' get current bind row
' only show Lable 1 if "ID" < = 1
Dim lbl1 As Label = e.Item.FindControl("Label1")
lbl1.Visible = OneRow("ID") <= 1
' only show Lable 2 if "ID" < = 2
Dim lbl2 As Label = e.Item.FindControl("Label2")
lbl2.Visible = OneRow("ID") <= 2
' if Active field = true, highlight hotelname as blue
If OneRow("Active") = True Then
Dim txtHotel As TextBox = e.Item.FindControl("txtHotel")
txtHotel.BackColor = Drawing.Color.AliceBlue
End If
End If
End Sub
And the results are now this:
So, note how in the data bind (item data bind) event, we get the ONE row used for that "instance" of the repeater. from that point on, the code is quite clean, and we have use of all data base columns - even ones NOT in the markup.
Regards,
Albert D. Kallal (Access MVP 2003-2017)
Edmonton, Alberta Canada