2013-10-10 38 views
0

我想讀取每個TextBox的值,但得到一個錯誤說: 'TextBox2'不是拖拉。由於其保護級別,它可能無法訪問。在GridView中使用TextBox給出的錯誤「'TextBox'不是拖延」在代碼後面

代碼前面:

<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 

的「點心strTextBoxValue1作爲」等線路工作正常,但值2和值3都表現出了同樣的錯誤說法他們沒有宣佈。

如何在後面的代碼中從TextBox2和TextBox3中讀取/檢索值?

回答

1

您無法直接訪問網格中的文本框/服務器控件,而是需要訪問將在DataRowBound事件中填充的aur填充行。

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; 
    } 
} 
+0

對不起,剛剛編輯了上面的「後面的代碼」粘貼以顯示按鈕被點擊時它是如何工作的。 – Rich

+0

@Adil我認爲你正在混淆你的VB和C#:) – MikeSmithDev

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 
+0

感謝代碼建議,但是'row'這個詞引發了與上面相同的錯誤,「並不是拖延的,由於它的保護級別,它可能無法訪問「。 - 我是否還需要添加其他內容? – Rich

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 
相關問題