我有一个 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