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:
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) 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