e.Item.DataItem in a ItemDataBound event (DataGrid)

M

MattB

I swear I've made this work no problem before and I'm not sure what's
gone wrong.

I have a form with a datagrid that I'm binding to a DatTable I generate
on the fly. If I just bind and load the page I can see all my data fine.

Now I want to add a textbox for each row and pre-populate that box with
values from my DataTable. So I created a OnItemDataBound event and it's
firing. My problem is that any time I try to reference data in the
source table I get a runtime error NullReferenceException.

Below is my ItemDataBound event. Can anyone see what my mistake(s)
is/are? It pukes when it hits that Case statement that refers to
e.Item.DataItem. I don't get it. Thanks!

Sub dgGuest_ItemDataBound(ByVal source As Object, ByVal e As
DataGridItemEventArgs)
Dim editCell As TableCell = e.Item.Controls(1), tb As New TextBox

'only bother with non-header or footer items
If (e.Item.ItemType = ListItemType.Item Or _
e.Item.ItemType = ListItemType.AlternatingItem) Then
End If

Select Case e.Item.DataItem("ColName")
Case "birth_date"
tb.Text = CType(e.Item.DataItem("val"),
Date).ToShortDateString
editCell.Controls.Add(tb)
Case Else
tb.Text = Convert.ToString(e.Item.DataItem("val"))
editCell.Controls.Add(tb)
End Select

End Sub
 
G

Guest

Pls put that inside


If (e.Item.ItemType = ListItemType.Item Or _
e.Item.ItemType = ListItemType.AlternatingItem) Then
Dim editCell As TableCell = e.Item.Controls(1), tb As New TextBox

End If
 
M

Matt Berther

Hello MattB,

Clearly, the problem here is that there is nothing inside your If condition.
Put the End If after the End Select.

The reason for this is that the first item is ListItemType.Header and it
does not have an e.Item.DataItem.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top