vb.net 如何在数据表中动态创建列并为其赋值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11240245/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to dynamically create columns in datatable and assign values to it?
提问by Anuya
I will have to create columns in datatable during runtime and assign values to it. How can i do it in vb.net. Any sample please...
我将不得不在运行时在数据表中创建列并为其分配值。我怎样才能在 vb.net 中做到这一点。任何样品请...
回答by RKK
If you want to create dynamically/runtime data table in VB.Net then you should follow these steps as mentioned below :
如果你想在 VB.Net 中创建动态/运行时数据表,那么你应该按照下面提到的这些步骤:
- Create Data table object.
- Add columns into that data table object.
- Add Rows with values into the object.
- 创建数据表对象。
- 将列添加到该数据表对象中。
- 将带有值的行添加到对象中。
For eg.
例如。
Dim dt As New DataTable
dt.Columns.Add("Id", GetType(Integer))
dt.Columns.Add("FirstName", GetType(String))
dt.Columns.Add("LastName", GetType(String))
dt.Rows.Add(1, "Test", "data")
dt.Rows.Add(15, "Robert", "Wich")
dt.Rows.Add(18, "Merry", "Cylon")
dt.Rows.Add(30, "Tim", "Burst")
回答by Tim Schmelter
What have you tried, what was the problem?
你试过什么,有什么问题?
Creating DataColumns
and add values to a DataTable
is straight forward:
创建DataColumns
和添加值到 aDataTable
很简单:
Dim dt = New DataTable()
Dim dcID = New DataColumn("ID", GetType(Int32))
Dim dcName = New DataColumn("Name", GetType(String))
dt.Columns.Add(dcID)
dt.Columns.Add(dcName)
For i = 1 To 1000
dt.Rows.Add(i, "Row #" & i)
Next
Edit:
编辑:
If you want to read a xml file and load a DataTable from it, you can use DataTable.ReadXml
.
如果要读取 xml 文件并从中加载 DataTable,可以使用DataTable.ReadXml
.