动态DataTable中的重复列错误

时间:2014-12-04 00:51:37

标签: asp.net vb.net loops if-statement for-loop

我在循环方面遇到了问题。我的阵列是

 Dim sec As String() = {"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", _
                            "U", "V", "W", "X", "Y", "Z", "A2", "B2", "C2", "D2", "E2", "F2", "G2", "H2", "I2", "J2", "K2", "L2", _
                            "M2", "N2", "O2", "P2", "Q2", "R2", "S2", "T2", "U2", "V2", "W2", "X2", "Y2", "Z2"}
    Dim coys As String() = {"(COY = 'A' OR COY = 'B')", "(COY = 'C' OR COY = 'D')", "(COY = 'E' OR COY = 'F')", "(COY = 'G' OR COY = 'H')"}

这是我的循环代码。

For x As Integer = 0 To coys.Length - 1
                cn.Open()
                'some codes
                cn.Close()
                For i As Integer = 0 To numsec2.SelectedValue - 1
                    Dim vHeader As String = sec(i)
                    If Not dt.Columns.Contains(vHeader) Then
                        Dim f As New Data.DataColumn(vHeader, GetType(System.String))
                        dt.Columns.Add(f)
                        f.AllowDBNull = True
                    ElseIf dt.Columns.Contains(vHeader) Then
                        Dim cc As New Data.DataColumn(vHeader, GetType(System.String))
                        dt.Columns.Add(cc)
                        cc.AllowDBNull = True
                    End If
                Next
            Next

我想要发生的是在运行此循环时它应该看起来像这样 例如,coys长度是4 并且numsec.selected值为2,这意味着它将每1个腼腆创建2个部分。

coy a包含贪婪的数据行。腼腆的许多数据。

姓名|腼腆| A | B | C | D | E | F | G | H |

约翰|一个

Kold |乙

迈克| ç

Loki | d

德祖| ë

数学| ˚F

循环| ģ

Tane | ħ

当我尝试运行上面的代码时,它会显示此错误

enter image description here

2 个答案:

答案 0 :(得分:2)

在循环的任何一个分支中你实际上都在添加任何数据;你只是添加一个列,冗余的一半时间。解决这两个问题,看看问题是否仍然存在。

答案 1 :(得分:0)

我的程序现在可以使用此代码

For i As Integer = 0 To numsec - 1
                Dim vHeader As String = sec(i)
                Dim asas As String = coys(x)
                If dt.Columns.Contains(vHeader & "_" & asas) Then
                    Dim f As New Data.DataColumn(vHeader & "_" & asas, GetType(System.String))
                    dt.Columns.Add(f)
                    f.AllowDBNull = True
                ElseIf Not dt.Columns.Contains(vHeader & "_" & asas) Then
                    Dim f As New Data.DataColumn(vHeader & "_" & asas, GetType(System.String))
                    dt.Columns.Add(f)
                    f.AllowDBNull = True
                End If
            Next