gridview findcontrol returning empty “”

廉价感情. 提交于 2019-12-24 01:47:23

问题


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


回答1:


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




回答2:


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.



来源:https://stackoverflow.com/questions/7089285/gridview-findcontrol-returning-empty

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!