When I first started programming in ASP.NET, the Formview was indispensable in displaying and manipulating data.  Eventually though, I needed access to individual fields within the Formview, and that's when I found many examples showing how to access field data  using the Ctype syntax to reference textboxes and other controls in my form.

As an example, to reference the value in a textbox in a Formview I would use the following statement:

This can get quite messy, and has always bugged me - I've ended up with asp pages full of invisible labels that I needed to store data.  Finding information on a more efficient way of doing this was surprisingly difficult, which is how this blog post came about in the first place.

Here is a better example, as you don't need to bind the data to a control:

Dim rowView As DataRowView = CType(formview1.DataItem, DataRowView) 
Dim myCategory As String = rowView("Category").ToString

And here is a shorthand way of doing this:

Dim myCategory As String = (DirectCast(formview1.DataItem, DataRowView))("Category")

You can check that your data exists before trying to accessing it by:

Dim rowView As DataRowView = CType(formview1.DataItem, DataRowView) 
If Not IsNothing(rowView) Then 
    ' Access your data... 
End If

Finally, within the formviews ItemUpdating, and ItemUpdated subroutines you can access your values through e.NewValue and e.OldValue.  So for only storing in your database the first 3 characters of the category you can use the following in your ItemUpdating sub:

e.NewValues("Category") = Left(e.OldValues("Category",3))

For the Inserting functions you use e.value.

Hopefuly this will help someone out there!

Bartek Marnane

Digg It!DZone It!StumbleUponTechnoratiRedditDel.icio.usNewsVineFurlBlinkList

Comments are closed