Reputation: 376
I am trying to read the values of each TextBox but get an error saying: 'TextBox2' is not delared. It may be inaccessible due to its protection level.
Code in front:
<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>
And the even simpler code behind:
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
The 'Dim strTextBoxValue1 As' etc line works fine, but value2 and value3 both show the same error saying they're not declared.
How do I read/retrieve the values from TextBox2 and TextBox3 in the code behind?
Upvotes: 0
Views: 948
Reputation: 195
As Adil said you need to find the control first and then you can transfer the value to somthing. example:
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
Upvotes: 0
Reputation: 148110
You can not access the textboxes/server controls in the grid directly instead you need to access the rows thoes aur populated are going to populated like in DataRowBound event.
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;
}
}
Upvotes: 1
Reputation: 12748
You can't do that cause you have one textbox for each row. You'll need to loop the rows to get to value of each one of them.
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
Upvotes: 1