如何将列添加到数据表数组中的表 [英] How to add columns to a table in an array of datatable

查看:60
本文介绍了如何将列添加到数据表数组中的表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数据表数组,可以存储10个表。我想为每个表添加列名。我使用下面的代码。但它显示错误文本调用未处理。我该如何摆脱这个。请帮助:



代码:

I have a data table array which can store 10 tables.i want to add column names to each table.i use the following code.But its showing an error text invocation was unhandled. How can i get rid of this.please help:

code:

DataTable[] studentsTable = new DataTable[10];
studentsTable[0].Columns.Add("Name", typeof(string));
studentsTable[0].Columns.Add("ID", typeof(string));
studentsTable[0].Columns.Add("Dob", typeof(string));

推荐答案





在你的例子中,你缺少对象初始化,见下文:

Hi,

In your example you are missing object initialization, see below:
DataTable[] studentsTable = new DataTable[10];
studentsTable[0] = new  DataTable();                      // you are missing this.
studentsTable[0].Columns.Add("Name", typeof(string));
studentsTable[0].Columns.Add("ID", typeof(string));
studentsTable[0].Columns.Add("Dob", typeof(string));





一个建议是,如果所有数据表数组都有相同的列,则使用for循环添加列名。



One suggestion is that if all array of datatable have same column then use for loop to add column name.

for(int i=0;i< studentsTable.Length;i++)
{
   studentsTable[i] = new  DataTable();
   studentsTable[i].Columns.Add("Name", typeof(string));
   studentsTable[i].Columns.Add("ID", typeof(string));
   studentsTable[i].Columns.Add("Dob", typeof(string));
}



希望它有所帮助。


Hope it helps.


这是一个如何向数据表添加列的示例对象: DataTable Class [ ^ ]



如果每个数据表的列相同,我建议您创建一个数据表,然后将其添加10次到列表< T> [ ^ ]泛型类,如果没有,根据需要多次创建和添加数据表。为什么列出< T> 泛型类,而不是数组?因为它表示可以通过索引访问的强类型对象列表;提供搜索,排序和操作列表的方法。
Here is an example how to add columns to a datatable object: DataTable Class[^]

If the columns for each datatable are the same, i would suggest you to create one datatable, then to add it 10 times to List<T>[^] generic class, if not, create and add datatable as many times as you need. Why List<T> generic class, instead array? Because it represents a strongly typed list of objects that can be accessed by index; provides methods to search, sort, and manipulate lists.


这篇关于如何将列添加到数据表数组中的表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆