【问题标题】:Column Name already belongs to datatable列名已经属于数据表
【发布时间】:2017-05-19 07:36:55
【问题描述】:

我尝试从一个 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.

作为我的 SP,我没有重复的列

【问题讨论】:

  • 您是否使用调试器查看了所有 cell.Text 值?
  • 是的,一切都正确,但数量上显示错误
  • 您是否检查过第一个循环中是否有两个标题单元格具有相同的文本“金额”?当您添加与另一列同名的第二列时,将在第一个循环中引发异常。你如何构建 GridView-header,它是静态的吗?
  • 没有 2 个带有文本“金额”的标题文本..我将数据从一个网格视图传输到另一个网格视图
  • @TimSchmelter ???????

标签: vb.net gridview webforms


【解决方案1】:

您评论说您确实有两个标题单元格具有相同的文本"Amount"。您不能将具有相同名称的两列添加到DataTable,因此您必须分配不同的名称或让它自动生成,例如Amount_2, Amount_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

【讨论】:

  • 那是很好的代码,我从未见过/使用过的东西。这是$"{colNameWithoutNum}_{num}" 在c# 中可用吗?我什至不知道该怎么称呼它。
  • @wazz 字符串插值,是的,它在 C# 中的使用时间比 VB 长。
  • 是的,它与 C# 中的语法相同,适用于 C#6 或 Visual Basic 14。但您也可以使用字符串连接或String.Format。 @AFriend:C# 和 VB.NET 在 VS 2015 中得到了相同的结果。
  • 对不起,我让你分心了。这不是我的操作。 ; )
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-03-11
  • 1970-01-01
  • 2014-07-03
  • 2018-08-13
相关资源
最近更新 更多