[英]how to create a datatable array/series
我想动态创建数据表数组。 根据 i 号,datagridview 中的表将保存到数据表中(如 table1、table2、table3 等)。 在另一种形式中,如果用户将 i 号写入文本框,datagridview 将使用正确的表(table1,table2...)填充
但是,如果我将 table(i) 声明为新数据表,我会收到“ Arrays cannot be declared with 'New' ”错误
如果我将表(i)声明为数据表,我在添加列时收到“ system.nullreferenceexception object 引用未设置为 object 的实例”错误
Sub add newtable()
Dim i As Integer = TextBox1.Text
Dim table(i) As New DataTable '!
With table(i).Columns
.Add("sample1", Type.GetType("System.String"))
.Add("sample2", Type.GetType("System.String"))
End With
table(i).Rows.Add("a", "b")
table(i).Rows.Add("c", "d")
End sub
然后
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
DataGridView1.DataSource = table(i)
End Sub
我知道这段代码不正确。 但我写这篇文章是为了更好地解释 mysef。
首先,现在和永远,打开 Option Strict。 项目属性 -> 编译选项卡。 也适用于未来的项目工具 -> 选项 -> 项目和解决方案 -> VB 默认值
一个DataSet
用来保存DataTable
。 List(Of DataTable)
可能更容易使用,因为您不必跟踪索引。 如果你真的需要一个数组,那么在Class
级别声明它。 我喜欢用复数来表示 collections 的名称。
Private tables As DataTable()
Sub addnewtable()
Dim i As Integer = CInt(TextBox1.Text)
tables(i) = New DataTable
With tables(i).Columns
.Add("sample1", Type.GetType("System.String"))
.Add("sample2", Type.GetType("System.String"))
End With
tables(i).Rows.Add("a", "b")
tables(i).Rows.Add("c", "d")
End Sub
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.