Question

Using Asp.net and VB.net. I have a DataList on a webpage. The datalist has a label control. I want to update the text of the label control in the first record with information obtained from the subsequent records as those subsequent records are databound. In other words, each time the datalist gets bound, I want to identify the label in the first record and then update the text of that label. I'm attempting to do this in the ItemDataBound by getting the ClientID of the label in the first record:

   Dim strMealPrice As String = CType(e.Item.FindControl("lblMealPrice"), Label).ClientID

and then hold that ClientID in a hidden label outside of the datalist.

 If lblhidMealHeaderID.Text = "" then
  lblhidMealHeaderID.Text = strMealPrice
 End if

Everything works up to this point.

Then each time the datalist ItemDataBound is fired I use findcontrol to try to update the label in the first record but I'm unsure how to format the findcontrol when using a variable for the label control's ClientID (lblhidMealHeaderID.text). But even when I hard code the ClientID of the label in the first record I can't get it to work.

 Dim tempLabel As Label = DataList1.FindControl("DataList1_ctl00_lblMealPrice")

or

Dim tempLabel As Label = CType(e.Item.FindControl("DataList1_ctl00_lblMealPrice"), Label)

I get a Object reference not set to an instance of an object. when I try to write to tempLabel.

As you can see I'm grasping here. First, is this the best way to do this - is the ItemDataBound where I should be attempting this? Perhaps you can't update previous records while the DataList is "binding" subsequent records. Second, is ClientID the way to do this - I see ClientID is used mostly for javascript? Third, how do I properly format the FindControl using ClientID?

Any and all help is greatly appreciated.

Was it helpful?

Solution

In ItemDataBound use this

If e.Item.ItemIndex = 0 Then
 CType(e.Item.FindControl("lblMealPrice"), Label).Text = strMealPrice
End If

Update

You can find the first label any time after binding by looping through its items.

For Each item as DataGridItem In dgGrid.Items
 CType(item.FindControl("lblMealPrice"), Label).Text = strMealPrice
Next
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top