Question How to cast e.NewValues item to DictionaryEntry in DetailsView

kpao

Active member
Joined
Apr 3, 2006
Messages
29
Programming Experience
Beginner
The following is part of my code:
VB.NET:
    Protected Sub DetailsView1_ItemUpdating(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.DetailsViewUpdateEventArgs) Handles DetailsView1.ItemUpdating
        For Each entry As DictionaryEntry in e.NewValues
                Response.Write(entry.Key.ToString())   'This works
        Next
        
        For i As Integer = 0 to e.NewValues.Count - 1
             Dim entry As DictionaryEntry = CType(DictionaryEntry, e.NewValues
(i))

             Response.Write(entry.Key.ToString()) 'Runtime error : Specified cast is not valid
        Next

    End Sub
It's strange. the e.NewValues item can be cast to DictionaryEntry when using for each loop. But not working in for loop. I need to use for loop because I would like to compare e.OldValues and e.NewValues. Anyone met this issue ever?
 
CType(DictionaryEntry, e.NewValues(i))
The first parameter to the CType function is the object expression, the second is the target type to convert/cast to, ie the opposite of yours. In VWD/VS this code give design time compiler errors.
 
Sorry, I have made a mistake about the CType. My original code is the following.
VB.NET:
 Protected Sub DetailsView1_ItemUpdating(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.DetailsViewUpdateEventArgs) Handles DetailsView1.ItemUpdating
    For Each entry As DictionaryEntry in e.NewValues
        Response.Write([COLOR="Red"]entry.Key.ToString()[/COLOR])   'This works
    Next
        
    For i As Integer = 0 to e.NewValues.Count - 1
      [COLOR="red"] Dim entry As DictionaryEntry = CType(e.NewValues(i), DictionaryEntry)[/COLOR]
       Response.Write([COLOR="red"]entry.Key.ToString()[/COLOR]) 'Runtime error : Specified cast is not valid
    Next

    End Sub
Anyway, I know how to cast a object using CType. My problem is the red highlight places are supposed to be same. These two for loops are doing same thing. But why the one using foreach could be worked. And another one could not be worked.
 
My original code is the following.
Weird, did you actually type that code in the post? :confused: There exists something called Copy & Paste in Windows... :)

About the InvalidCastException, I don't know why it happens here, I saw this code somewhere that copies the entries to an array, indexing this doesn't throw the exception:
VB.NET:
Dim entries(e.NewValues.Count - 1) As DictionaryEntry
e.NewValues.CopyTo(entries, 0)

Dim entry As DictionaryEntry = entries(i)
 
Back
Top