2

我有一个 DataGrid,每次用户在另一个数据网格中选择和项目时都会动态创建它。我错过了最后一步,这让我头痛了 8 小时。按下按钮时,我需要阅读每一行。基本上用户按下按钮,程序应该读取每一行的值(产品ID或名称[在这种情况下是唯一的]),为其分配一个“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

结束子

更新的按钮处理程序

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
4

2 回答 2

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 cast替换为您想要的Control类型

//刚刚编译了代码,它工作正常

问候

于 2013-05-16T17:01:34.577 回答
-1

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

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

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
于 2013-05-16T16:59:12.097 回答