0

我正在尝试读取每个 TextBox 的值,但收到一条错误消息:'TextBox2' is not 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 的值?

4

3 回答 3

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
于 2013-10-10T15:36:41.133 回答
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;
    }
}
于 2013-10-10T15:25:53.647 回答
0

正如阿迪尔所说,您需要先找到控件,然后才能将值转移到某物。例子:

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
于 2013-10-10T15:30:50.023 回答