在GridView文本框TemplateField中获取值

时间:2013-10-02 19:33:46

标签: asp.net vb.net gridview findcontrol

我有一个名为Default.aspx的asp.net页面,它的主页面是Site.master。在Default.aspx中,我添加了一个包含3个数据绑定字段和1个Templatefield的gridview,然后在此模板字段中拖动了一个TextBox。

Image Templatefield Editor

我正在尝试使用FindControl方法获取此gridview中每行的文本框值,但它返回Nothing。

以下是我用来检索这些值的代码:

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

注意:我正在使用masterPages,我认为这会导致问题。

[编辑]

在Page_load事件中,为了绑定gridview,我正在使用代码:

        GridView1.DataSource = f.xDa
        GridView1.DataBind()

在Button1中,我添加了代码:

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

但我总是得到一个空的文本框。

谢谢大家!

2 个答案:

答案 0 :(得分:4)

您需要将Page_Load代码更新为:

If Not IsPostBack Then
    GridView1.DataSource = f.xDa
    GridView1.DataBind()
End If

当您的代码进入Button_Click事件时,它已经使用数据库中的数据重新填充GridView(覆盖用户键入TextBox的内容)。

我上面添加的代码导致数据仅在第一次加载 - 然后ASP.NET视图状态处理确保GridView的状态保持最新。

答案 1 :(得分:0)

我遇到了类似的问题,但是我的gridview没有在Page_Load中呈现,因此我无法将“If Not IsPostBack”绑定添加到Page_Load,因为我正在使用的SQL数据集尚未声明。

如果您不能使用Page_Load gridview数据绑定,而不是FindControl并按名称调用文本框,尝试这样的操作可能会有效:

For Each gvr As GridViewRow In GridView1.Rows

    Dim txt As String = CType(gvr.Cells(0).Controls(0), TextBox).Text
    MsgBox(txt)

Next

单元格(0)中的(0)是您尝试访问的gridview中的列号。因此,例如,如果“TextBox1”是第1列使用Cells(0),如果是第2列则使用Cells(1),依此类推。这允许检索文本框中的文本,而无需在Page_Load

中添加其他部分
相关问题