Why is my TextBox Column in my GridView not found with a FindControl

时间:2019-01-09 21:54:22

标签: asp.net vb.net

I have a GridView that displays correctly. I have a GridView in my aspx file:

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" Font="8" />

In my code.behind I also have:

If Not IsPostBack Then

            Dim boundColumn As BoundField = New BoundField With {
                .HeaderText = "Product Name",
                .DataField = "ProductName"
            }
            GridView1.Columns.Add(boundColumn)

            Dim txtBkWhColumn As TemplateField = New TemplateField With {
                .ItemTemplate = New TextColumn("myTextBox1"),
                .HeaderText = "BK/WH"
            }
            GridView1.Columns.Add(txtBkWhColumn)

            Dim txtBlPuColumn As TemplateField = new TemplateField With {
                .ItemTemplate = new TextColumn("myTextBox2"),
                .HeaderText = "BL/PU"
            }
            GridView1.Columns.Add(txtBlPuColumn)

...

Class TextColumn
Implements ITemplate

Private ReadOnly _myName As String

Public Sub New(myName As String)
    _myName = myName
End Sub

Public Sub InstantiateIn(container As Control) Implements ITemplate.InstantiateIn
    Dim txt As New TextBox
    txt.ID = _myName
    txt.Columns = 1
    container.Controls.Add(txt)
End Sub
End Class

But when I try to read the content of the textbox it is null

For Each row As GridViewRow In GridView1.Rows
    Debug.WriteLine($"Row {row.Cells(0).Text}")
    Dim bkwh As TextBox = row.Cells(1).FindControl("myTextBox1") 
    Dim blpu As TextBox = row.Cells(2).FindControl("myTextBox2") 

    Dim countBkWh As Int32
        If (Not String.IsNullOrEmpty(bkwh.Text)) Then
            countBkWh = Int32.Parse(bkwh.Text)
            Debug.WriteLine($"Count of BLWH: {countBkWh}")
            sb.Append(" " & $"BLWH:{countBkWh}")
            total = total + countBkWh
        End If

I get an Null Reference exception on this last if statement saying bkwh is not an instance of an object

1 个答案:

答案 0 :(得分:0)

就我而言,我需要将列定义从Page_Load移到Page_Init。我不知道为什么行得通,但是行得通。