问题
I have an asp.net page called Default.aspx, and it's master page is Site.master. In the Default.aspx, i added a gridview with 3 databound fields and 1 Templatefield, and then, dragged a TextBox inside this templatefield.

I'm trying to get the textbox values for each row in this gridview, using the FindControl method, but it's returning Nothing.
Here is the code that i'm using to retrieve these values:
For Each gvr As GridViewRow In GridView1.Rows
Dim tb As TextBox = DirectCast(gvr.FindControl("TextBox1"), TextBox)
Dim txt As String = tb.Text
MsgBox(txt)
Next
Note: I'm using masterPages, and i'm thinking this is causing the problem.
[edit]
In the Page_load event, to bound the gridview, i'm using the code:
GridView1.DataSource = f.xDa
GridView1.DataBind()
In the Button1, I've added the code:
For Each gvr As GridViewRow In GridView1.Rows
Dim tb As TextBox = DirectCast(gvr.FindControl("TextBox1"), TextBox)
Dim txt As String = tb.Text
MsgBox(txt)
Next
But i'm Always getting an empty textbox.
Thank's everybody!
回答1:
You need to update your Page_Load
code to this:
If Not IsPostBack Then
GridView1.DataSource = f.xDa
GridView1.DataBind()
End If
By the time your code gets to the Button_Click
event, it has already repopulated the GridView with data from your database (overwriting what your user typed into the TextBox).
The code I've added above causes the data to be loaded only the first time - then the ASP.NET viewstate handles making sure the state of the GridView is kept up-to-date.
回答2:
I had a similar problem, but my gridview wasn't rendered at Page_Load so I couldn't add the "If Not IsPostBack" bindings to the Page_Load as the SQL dataset I was using wasn't yet declared.
Instead of the FindControl and calling your textbox by name, trying something like this might work if you can't use the Page_Load gridview databinding:
For Each gvr As GridViewRow In GridView1.Rows
Dim txt As String = CType(gvr.Cells(0).Controls(0), TextBox).Text
MsgBox(txt)
Next
The (0) in the Cells(0) is the column number in your gridview that you are trying to access. So for example If "TextBox1" is the 1st column use Cells(0), if it is the 2nd column use Cells(1) and so on. This allows the text in the textbox to be retrieved without having to add an additional section in the Page_Load
来源:https://stackoverflow.com/questions/19145323/get-values-in-gridview-textbox-templatefield