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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 16:11:03  来源:igfitidea点击:

How to dynamically create columns in datatable and assign values to it?

vb.netdatatablevb.net-2010

提问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 DataColumnsand add values to a DataTableis 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.