如何以编程方式创建DataTable?我有以下代码,我想创建一个像Java一样的数据表,这将允许我创建一个表,我可以使用CSV(,)的数据,如姓名,地址和电话号码。
代码:
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
private System.Data.DataSet dataSet;
System.Data.DataTable table = new DataTable("ParentTable");
public Form1()
{
InitializeComponent();
}
private void MakeParentTable()
{
DataColumn column;
DataRow row;
column = new DataColumn();
column.DataType = System.Type.GetType("System.Int32");
column.ColumnName = "id";
column.ReadOnly = true;
column.Unique = true;
table.Columns.Add(column);
column = new DataColumn();
column.DataType = System.Type.GetType("System.String");
column.ColumnName = "ParentItem";
column.AutoIncrement = false;
column.Caption = "ParentItem";
column.ReadOnly = false;
column.Unique = false;
table.Columns.Add(column);
DataColumn[] PrimaryKeyColumns = new DataColumn[1];
PrimaryKeyColumns[0] = table.Columns["id"];
table.PrimaryKey = PrimaryKeyColumns;
dataSet = new DataSet();
dataSet.Tables.Add(table);
for (int i = 0; i<= 2; i++)
{
row = table.NewRow();
row["id"] = i;
row["ParentItem"] = "ParentItem " + i;
table.Rows.Add(row);
}
}
private void Form1_Load(object sender, EventArgs e)
{
MakeParentTable();
}
}
}
答案 0 :(得分:0)
使用FileStream和StreamReader从csv文件中读取数据。我看到您在代码中以编程方式创建了DataTable。