按下按钮,读取GridView中的每一行

时间:2013-05-16 16:46:47

标签: asp.net vb.net

我有一个DataGrid,每次用户选择另一个数据网格中的项目时都会动态创建。我错过了一个让我长达8小时头痛的最后一步。按下按钮时,我需要读取每一行。基本上用户按BUTTON并且程序应该读取每一行的值(productID或Name [在这种情况下是唯一的]),为其分配“1”值,将信息插入数据库,并对每一行重复该过程。我到了这里:

Protected Sub btnProcess_Click(sender As Object, e As EventArgs) Handles btnProcesss.Click
    For Each GridViewRow In GridView2.Rows

        'EmptySpace
    Next
End Sub

就是这样。我知道我有正确的循环(对吗?)但我不知道要添加什么,因为我不能使用这个代码例如:

Dim findrow = e.Row.Cell(cellIndex).FindControl("ControlID")

因为它在e.Row中给我一个错误。任何有关如何进行的帮助将不胜感激:)。

编辑:在SelectedIndexChanged ...

下生成列的代码
  If GridView2.Rows.Count = 0 Then
            '  dt = New DataTable()
            dt.Columns.Add(New DataColumn("Name", GetType(System.String)))
            dt.Columns.Add(New DataColumn("Price", GetType(System.String)))
        Else
            dt = DirectCast(Session("DataTable"), DataTable)
        End If

添加了整个代码......

Protected Sub GridView1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles GridView1.SelectedIndexChanged

    .
    Dim row = GridView1.SelectedRow
    If Not row Is Nothing AndAlso IsNumeric(row.Cells(3).Text) Then
        Dim Price As Double = CDbl(row.Cells(3).Text)
        Dim Name As String = CStr(row.Cells(2).Text)



        If GridView2.Rows.Count = 0 Then
            '  dt = New DataTable()
            dt.Columns.Add(New DataColumn("Name", GetType(System.String)))
            dt.Columns.Add(New DataColumn("Price", GetType(System.String)))
        Else
            dt = DirectCast(Session("DataTable"), DataTable)
        End If
        Session("DataTable") = dt

        Dim dr1 As DataRow = dt.NewRow()
        dr1(0) = Name.ToString
        dr1(1) = CDbl(Price.ToString)
        dt.Rows.Add(dr1)
        GridView2.DataSource = dt
        GridView2.DataBind()




    End If

End Sub

更新了按钮处理程序

Protected Sub btnProcess_Click(sender As Object, e As EventArgs) Handles btnProcess.Click

    For Each row As GridViewRow In GridView2.Rows

        Dim str As String = TryCast(row.FindControl("Name"), Label).Text
   'For testing purposes a MsgBox
        MsgBox(str)

    Next

2 个答案:

答案 0 :(得分:4)

正确的按钮事件处理是:

Protected Sub btnProcess_Click(sender As Object, e As EventArgs) Handles btnProcesss.Click

    For Each row As GridViewRow In Grid1.Rows

        Dim _str As String = TryCast(row.FindControl("Control1"), Label).Text
    Next

//为您的问题的第二部分添加:

要获取名称列中的值:

Dim _NameColumnValue = TryCast(row.Cells(0), DataControlFieldCell).Text

//只需将Label强制转换为您想要的Control类型

//只是编译了代码并且工作正常

问候

答案 1 :(得分:-1)

而不是在您的示例中使用e.Row,而是使用For Each循环中的变量。

我稍微更新了你的代码以使用“gvr”,以免与Type混淆。

Protected Sub btnProcess_Click(sender As Object, e As EventArgs) Handles btnProcesss.Click
    For Each gvr as GridViewRow In GridView2.Rows

        ' (BAD CODE - SEE COMMENTS)
        Dim findrow = gvr.Cell(cellIndex).FindControl("ControlID")

        ' (CORRECTED CODE)
        Dim MyTextBox as TextBox = CType(gvr.FindControl("MyTextBox"), TextBox) 

    Next
End Sub