好吧,我现在说它很简单你有一个多维数组,我尝试使用以下代码填充我的数据表:
System.Data.DataTable _myDataTable =new System.Data.DataTable();
for (int j=0; j < ele; j++)
{
_myDataTable.Columns.Add();
for (int i = 0; i < caract+1; i++)
{
row[i]=(datar[j,i].ToString());
}
_myDataTable.Rows.Add(row);
}
Run Code Online (Sandbox Code Playgroud)
我的数组名称是datar
我收到的错误:
System.IndexOutOfRangeException: cant find column 1.
Run Code Online (Sandbox Code Playgroud)
我究竟做错了什么?顺便说一下:我使用的是C#,asp.net,而不是Visual Studio.
Fil*_*urt 19
正如chiffre所指出的,你实际上有3个问题:在开始添加行之前你必须添加所有列,然后你必须创建一个DataRow
才能将它添加到你的行中DataTable
.您的第三个问题是您的行维度计数器caract+1
,它将产生IndexOutOfRange异常.
DataTable _myDataTable = new DataTable();
// create columns
for (int i = 0; i < ele; i++)
{
_myDataTable.Columns.Add();
}
for (int j = 0; j < caract; j++)
{
// create a DataRow using .NewRow()
DataRow row = _myDataTable.NewRow();
// iterate over all columns to fill the row
for (int i = 0; i < ele; i++)
{
row[i] = datar[i, j];
}
// add the current row to the DataTable
_myDataTable.Rows.Add(row);
}
Run Code Online (Sandbox Code Playgroud)
小智 6
扩展方法怎么样
static class HappyExtEnding
{
public static DataTable ToDataTable<T>(this T [] students)
{
if (students == null || students.Length == 0) return null;
DataTable table = new DataTable();
var student_tmp = students[0];
table.Columns.AddRange(student_tmp.GetType().GetFields().Select(field => new DataColumn(field.Name, field.FieldType)).ToArray());
int fieldCount = student_tmp.GetType().GetFields().Count();
students.All(student =>
{
table.Rows.Add(Enumerable.Range(0, fieldCount).Select(index => student.GetType().GetFields()[index].GetValue(student)).ToArray());
return true;
});
return table;
}
}
Run Code Online (Sandbox Code Playgroud)
用法
Student[] students = {
new Student { Id = 1, Name = "Joe Rattz", Address = "Sriram Apartments" },
new Student { Id = 6, Name = "Ulyses Hutchens", Address = "Sriram Apartments" },
new Student { Id = 19, Name = "Bob Tanko", Address = "Sriram Apartments" },
new Student { Id = 45, Name = "Erin Doutensal", Address = "Sriram Apartments" },
new Student { Id = 1, Name = "Joe Rattz", Address = "Sriram Apartments" },
new Student { Id = 12, Name = "Bob Mapplethorpe", Address = "Sriram Apartments" },
new Student { Id = 17, Name = "Anthony Adams", Address = "Sriram Apartments" },
new Student { Id = 32, Name = "Dignan Stephens Mark", Address = "Sriram Apartments" },
new Student { Id = 1232, Name = "Dignan Stephens", Address = "Sriram Apartments Henry Labamba Beligi" },
new Student { Id = 132, Name = "Neha Dhupia", Address = "Sriram Apartments 123456" },
new Student { Id = 132, Name = "", Address = "Sriram Apartments 123456" },
new Student { Id = 133, Name = "", Address = "Sriram Apartments 123456" },
new Student { Id = 134, Name = "Neha Dhupia", Address = "" },
new Student { Id = 134, Name = "Shradha Kapoor", Address = "Mumbai" }
};
//ParallelQuery<int>
DataTable dtTmp = students.ToDataTable() ;
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
75689 次 |
最近记录: |