2

i am trying to read from a textbox within a gridview by using this code

    protected void Button1_Click(object sender, EventArgs e)
    {
        foreach (GridViewRow row in GridView1.Rows)
        {
            string textBoxText = ((TextBox)row.FindControl("numTC")).Text;
            Response.Write(textBoxText);

        }
    }

this code keeps returning "" (empty)

any idea why this is hapenning?

Thanks

Karl
  • 781
  • 2
  • 9
  • 26

2 Answers2

4

Make sure that you are not re-binding the GridView on the PostBack of the page. This may be the issue.

EDITS

Make sure that the code for Binding the GridView is within the code below:

C#

if ( !Page.IsPostBack ){
    // Code to bind the control
}

VB

If Not Page.IsPostBack Then
    ' Code to bind the control
End If

Otherwise what happens is that the controls is "rebuilt" and the values are all lost within the TextBox's

Tim B James
  • 20,084
  • 4
  • 73
  • 103
1

UPDATE:

For testing purposes, try doing GridView1.DataBind(); at the begining of your method.

Try debugging like this:

Set a breakpoint at the end of the Button1_Click method.

Run the site in debug mode (F5).

When executions stops at end of Button1_Click, open the Immediate Window located at bottom of screen.

Type there:

GridView1.Rows and see if it contains the number of rows it should.

Should be something like:

System.Web.UI.WebControls.GridViewRowCollection} Count: 53 <-- number of rows

If it does return more than 0 rows then type:

GridView1.Rows[0].Controls and see if it returns the right number of controls on a row.

I could access controls on a row directly using GridView1.Rows[2].Controls[n] where n is the order of the control in the row.

Also try (TextBox)GridView1.Rows[0].FindControl("numTC") and see what it returns.

Răzvan Flavius Panda
  • 21,730
  • 17
  • 111
  • 169
  • ive done as you said, the number of rows shows as 79, and the (TextBox)GridView1.Rows[0].FindControl("numTC") still returns "" – Karl Aug 17 '11 at 08:15
  • @Karl: the only thing i can think of is that the control you are searching has a different ID from "numTC", i made that mistake once and didn't notice :) – Răzvan Flavius Panda Aug 17 '11 at 08:19
  • ive tried that too..but unfortunatley it wasnt the case, ill keep trying to see whats wrong, thanks anyway – Karl Aug 17 '11 at 08:23
  • @Karl: does GridView1.Rows[0].FindControl("numTC") return null? – Răzvan Flavius Panda Aug 17 '11 at 08:34
  • when i do response.write, it just returns System.Web.UI.WebControls.TextBox – Karl Aug 17 '11 at 08:41
  • @Karl: i mean to use the command GridView1.Rows[0].FindControl("numTC") in Immediate Window, if it returns null it means it couldn't find the control. Does it return null? – Răzvan Flavius Panda Aug 17 '11 at 08:43
  • problem solved, it was because the data was rebinding every time i pressed the button, thanks for your help – Karl Aug 17 '11 at 08:49