首页 > 代码库 > 数组转DataTable

数组转DataTable


using System;
using System.Data;

namespace ArrayToDataTable
{
class ArrayToDataTable
{
/// <summary>
/// 把一个一维数组转换为DataTable
/// </summary>
public static DataTable Convert(string ColumnName, string[] Array)
{
DataTable dt = new DataTable();
dt.Columns.Add(ColumnName, typeof(string));

for (int i = 0; i < Array.Length; i++)
{
DataRow dr = dt.NewRow();
dr[ColumnName] = Array[i].ToString();
dt.Rows.Add(dr);
}
return dt;
}

/// <summary>
/// 反一个M行N列的二维数组转换为DataTable
/// </summary>
public static DataTable Convert(string[] ColumnNames, string[,] Arrays)
{
DataTable dt = new DataTable();

foreach (string ColumnName in ColumnNames)
{
dt.Columns.Add(ColumnName, typeof(string));
}

for (int i1 = 0; i1 < Arrays.GetLength(0); i1++)
{
DataRow dr = dt.NewRow();
for (int i = 0; i < ColumnNames.Length; i++)
{
dr[i] = Arrays[i1, i].ToString();
}
dt.Rows.Add(dr);
}
return dt;
}
/// <summary>
/// 反一个M行N列的二维数组转换为DataTable
/// </summary>
public static DataTable Convert(string[,] Arrays)
{
DataTable dt = new DataTable();

int a = Arrays.GetLength(0);
for (int i = 0; i < Arrays.GetLength(1); i++)
{
dt.Columns.Add("col" + i.ToString(), typeof(string));
}

for (int i1 = 0; i1 < Arrays.GetLength(0); i1++)
{
DataRow dr = dt.NewRow();
for (int i = 0; i < Arrays.GetLength(1); i++)
{
dr[i] = Arrays[i1, i].ToString();
}
dt.Rows.Add(dr);
}
return dt;
}
}
}
调用
[csharp] view plaincopyprint?
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace ArrayToDataTable
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)
{
dataGridView1.DataSource = ArrayToDataTable.Convert("haha", new string[] { "1", "2", "3", "4", "5", "6" });
}

private void button2_Click(object sender, EventArgs e)
{
string[,] array3D = {

{ "1", "数组转DataTable 1", "0"},

{ "2", "数组转DataTable 2", "1"},

{ "3", "数组转DataTable 3", "1"},

{ "4", "数组转DataTable 4", "2"},

{ "5", "数组转DataTable 5", "2"},

{ "6", "数组转DataTable 6", "5"},

};
dataGridView1.DataSource = ArrayToDataTable.Convert(new string[] { "haha1", "haha2", "haha3" }, array3D);
}

private void button3_Click(object sender, EventArgs e)
{
string[,] array3D = {

{ "1", "数组转DataTable 1", "0"},

{ "2", "数组转DataTable 2", "1"},

{ "3", "数组转DataTable 3", "1"},

{ "4", "数组转DataTable 4", "2"},

{ "5", "数组转DataTable 5", "2"},

{ "6", "数组转DataTable 6", "5"},

};
dataGridView1.DataSource = ArrayToDataTable.Convert(array3D);
}
private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
System.Diagnostics.Process.Start("Iexplore.exe", "http://www.yongfa365.com/");

}
}
}

 

数组转DataTable