在GridView中使用TextBox会导致错误“'TextBox'未在代码中声明”

时间:2013-10-10 15:23:42

标签: asp.net vb.net

我正在尝试读取每个TextBox的值,但收到错误说: 'TextBox2'不是delared。由于其保护级别,它可能无法访问。

前面的代码:

<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:Button ID="Button1" runat="server" Text="Button1" />

<asp:SqlDataSource ID="SqlDataSource1" runat="server"></asp:SqlDataSource>
<asp:GridView ID="GridView1" runat="server" DataSourceID="SqlDataSource1">
    <Columns>
        <asp:TemplateField HeaderText="equipment_note" SortExpression="equipment_note">
            <EditItemTemplate>
                <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
            </EditItemTemplate>
            <ItemTemplate>
                <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
    <EmptyDataTemplate>
        <asp:TextBox ID="TextBox3" runat="server"></asp:TextBox>
        <asp:Button ID="Button3" runat="server" Text="Button2" />
    </EmptyDataTemplate>
</asp:GridView>

更简单的代码背后:

Protected Sub Button1_Click(sender As Object, e As System.EventArgs) Handles Button1.Click
    Dim strTextBoxValue1 As String = TextBox1.Text
    Dim strTextBoxValue2 As String = TextBox2.Text
    Dim strTextBoxValue3 As String = TextBox3.Text
    Response.Write(strTextBoxValue1)
End Sub

'Dim strTextBoxValue1 As'等行工作正常,但是value2和value3都显示相同的错误,表示它们未被声明。

如何在后面的代码中读取/检索TextBox2和TextBox3中的值?

3 个答案:

答案 0 :(得分:1)

您无法直接访问网格中的文本框/服务器控件,而是需要访问填充的行,这些行将填充在DataRowBound事件中。

void CustomersGridView_RowDataBound(Object sender, GridViewRowEventArgs e)
{
    if(e.Row.RowType == DataControlRowType.DataRow)
    {
        // Display the company name in italics.
        Dim TextBox1 As TextBox = e.Row.FindControl("TextBox1") As TextBox;
    }
}

答案 1 :(得分:1)

您无法做到这一点,因为每行都有一个文本框。您需要循环行以获取每个行的值。

Protected Sub Button1_Click(sender As Object, e As System.EventArgs) Handles Button1.Click

        For Each row As GridViewRow In GridView1.Rows
    strTextBoxValue2 = CType(row.FindControl("TextBox2"), TextBox).Text
        Next

    End Sub

答案 2 :(得分:0)

正如Adil说你需要先找到控件然后你可以将值转移到somthing。 例如:

For i As Integer = 0 To GridView1.Rows.Count - 1
        Dim row As GridViewRow = GridView1.Rows(i)
        Dim strTextBoxValue2 as string = CType(row.Cells(0).FindControl("TextBox2"), Textbox).Text
Next