在Visual Basic中将GridViewRow数据导入DataRow

时间:2012-09-09 00:24:47

标签: vb.net

下面是我试图用来将GridViewRow中的值转换为DataRow对象的循环(使用Visual Basic的Godforsaken语言)。但是,在这一行:

                dr(i) = r.Cells(i).Text

我不断收到以下错误消息:

the value of type string cannot be converted to system.data.datarow

有人能指出我正确的方向如何做到这一点?

        Dim rows As New List(Of GridViewRow)()

        For Each item As GridViewRow In grdExpProd.Rows
            rows.Add(item)
        Next

        Dim value As Integer = rows.Count

        Dim dt As New DataTable()


        For index As Integer = value - 1 To 0 Step -1
            Dim dr As DataRow()
            Dim r As GridViewRow = rows(index)

            For i As Integer = 0 To r.Cells.Count - 1
                dr(i) = r.Cells(i).Text
            Next

            dt.Rows.Add(dr)
        Next

3 个答案:

答案 0 :(得分:1)

我相信您需要将文本添加到DataRows Item Property,这样您才能访问DataRow的各个单元格。您还需要将GridRowView中存在的列添加到新的DataTable

For i = 1 To rows(0).Cells.Count
    dt.Columns.Add("Header" & i)
Next

For index As Integer = value - 1 To 0 Step -1
    Dim dr As DataRow = dt.NewRow()
    Dim r As GridViewRow = rows(index)

    For i As Integer = 0 To r.Cells.Count 
        dr.Item(i) = r.Cells(i).Text
    Next

    dt.Rows.Add(dr)
Next

答案 1 :(得分:0)

您意外地将dr创建为DataRow对象数组,而不是单个DataRow对象。尝试替换

Dim dr As DataRow()

Dim dr As New DataRow()

答案 2 :(得分:0)

尝试替换

Dim dr As DataRow()

Dim dr As DataRow = dt.NewRow()

另外,正如另一张海报所指出的那样,在尝试向其中添加行之前,需要在数据表中创建列。