列名已经属于datatable

时间:2017-05-19 07:36:56

标签: vb.net gridview webforms

我尝试从一个gridview复制到另一个gridview 我试试这个

 Dim dt As New DataTable()

    For Each cell As TableCell In GridView1.HeaderRow.Cells
        dt.Columns.Add(cell.Text)
    Next

    For Each row As GridViewRow In GridView1.Rows
        dt.Rows.Add()
        For i As Integer = 0 To row.Cells.Count - 1
            dt.Rows(row.RowIndex)(i) = row.Cells(i).Text

        Next
    Next

    GridView2.DataSource = dt
    GridView2.DataBind()

但这显示错误

A column named 'Amount' already belongs to this DataTable.

在哪里,我不会有重复的列

1 个答案:

答案 0 :(得分:1)

您评论说您确实有两个标题单元格具有相同的文字"Amount"。您不能将两个具有相同名称的列添加到DataTable,因此您必须指定一个不同的名称或让它自动生成,例如。 Amount_2Amount_3,...:

此版本使用SubstringLastIndexOf处理列名称可能包含下划线的情况:

For Each cell In tableCells
    Dim colName = cell
    While dt.Columns.Contains(colName)
        Dim lastUnderscoreIndex = colName.LastIndexOf("_"c)
        Dim colNameWithoutNum = If(lastUnderscoreIndex > -1, colName.Remove(lastUnderscoreIndex), colName)
        Dim numPart = If(lastUnderscoreIndex > -1, colName.Substring(lastUnderscoreIndex + 1), "")
        Dim num As Int32 = If(Int32.TryParse(numPart, num), num + 1, 2)
        colName = $"{colNameWithoutNum}_{num}"
    End While
    dt.Columns.Add(colName)
Next