Dim dt As New DataTable
dt.Clear()
For i As Integer = 0 To listbox2.items.Count - 1
If ListBox2.text = "X,Y Coordinate" Then
dt.Columns.Add("X Coordinate")
dt.Columns.Add("Y Coordinate")
ElseIf ListBox2.text = "Latitude, Longitude" Then
dt.Columns.Add("Latitude")
dt.Columns.Add("Longitude")
End If
Next
Dim mr As DataRow
mr = dt.NewRow
mr("X Coordinate") = "sdsf"
mr("Y Coordinate") = "sdfsdf"
mr("Latitude") = "AsDASDASD"
mr("Longitude") = "AsDASDASD"
dt.Rows.Add(mr)
GridView1.DataSource = dt
GridView1.DataBind()
现在坚持这个错误几个小时。查看其他堆栈溢出问题帖子,但没有人回答为什么我得到这个问题。
答案 0 :(得分:1)
首先,您必须按列表ListBox2.Items(i).ToString()的项目进行测试,您还可以测试数据表中是否存在列:
If ListBox2.Items(i).ToString() = "X,Y Coordinate" Then
If (Not columns.Contains("X Coordinate")) Then dt.Columns.Add("X Coordinate")
If (Not columns.Contains("Y Coordinate")) Then dt.Columns.Add("Y Coordinate")
ElseIf ListBox2.text = "Latitude, Longitude" Then
If (Not columns.Contains("Latitude")) Then dt.Columns.Add("Latitude")
If (Not columns.Contains("Longitude")) Then dt.Columns.Add("Longitude")
End If
答案 1 :(得分:0)
错误在循环中。始终检查ListBox的相同文本。我知道你想要比较ListBox的每个元素的文本。
Dim dt As New DataTable
dt.Clear()
For i As Integer = 0 To listbox2.items.Count - 1
If ListBox2.Items(i).ToString() = "X,Y Coordinate" Then
dt.Columns.Add("X Coordinate")
dt.Columns.Add("Y Coordinate")
ElseIf ListBox2.Items(i).ToString() = "Latitude, Longitude" Then
dt.Columns.Add("Latitude")
dt.Columns.Add("Longitude")
End If
Next
Dim mr As DataRow
mr = dt.NewRow
mr("X Coordinate") = "sdsf"
mr("Y Coordinate") = "sdfsdf"
mr("Latitude") = "AsDASDASD"
mr("Longitude") = "AsDASDASD"
dt.Rows.Add(mr)
GridView1.DataSource = dt
GridView1.DataBind()