Click here to Skip to main content
15,895,142 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
This is the error:

Unable to cast object of type 'System.Web.UI.WebControls.TemplateField' to type 'System.Web.UI.WebControls.BoundField'.System Error.


VB
Protected Sub GriView1_RowCreated(ByVal sender As Object, ByVal e As GridViewRowEventArgs) Handles GridView1.RowCreated
        For Each cell As TableCell In e.Row.Cells
            If Not String.IsNullOrEmpty(cell.Text) AndAlso (cell.Text <> "") Then
                Dim field As BoundField = CType(CType(cell, DataControlFieldCell).ContainingField, BoundField)
                If (field.DataField = "Name") Then
                    field.ReadOnly = True
                End If
            End If
        Next
    End Sub
Posted
Updated 11-Jun-15 5:25am
v3
Comments
Sergey Alexandrovich Kryukov 11-Jun-15 11:34am    
Who told you "this code" would be "working on C#"? Probably it wasn't "this". :-)
—SA

Please see my comment to the question. It could not be "this code" it if was "working". You can always automatically translate between C# and VB.NET. Please see my past answer: Code Interpretation, C# to VB.NET[^].

—SA
 
Share this answer
 
The error message is quite clear - you have a <asp:TemplateField> in your grid, which is not a <asp:BoundField>, so your attempt to cast it as such will fail.

The equivalent code would also fail in C#.

To make it work in C#, you would use the as operator[^] and test for null. In VB.NET, the TryCast operator[^] performs a similar function:
VB.NET
Protected Sub GriView1_RowCreated(ByVal sender As Object, ByVal e As GridViewRowEventArgs) Handles GridView1.RowCreated
    For Each cell As TableCell In e.Row.Cells
        ' No need to compare to an empty string as well; 
        ' this has already been taken care of by the "IsNullOrEmpty" call.
        If Not String.IsNullOrEmpty(cell.Text) Then 
            Dim fieldCell As DataControlFieldCell = TryCast(cell, DataControlFieldCell)
            If fieldCell IsNot Nothing Then
                Dim field As BoundField = TryCast(fieldCell.ContainingField, BoundField)
                If field IsNot Nothing AndAlso field.DataField = "Name" Then
                    field.ReadOnly = True
                End If
            End If
        End If
    Next
End Sub
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900