如何创建动态数据表?

时间:2012-05-01 07:13:25

标签: c# datatable

我想动态创建一个数据表列表,如:

 DataTable[] Mydt = new DataTable();

并填写如下:

Mydt[i] = .....

你知道c#中是否存在这样的语法吗?

由于

1 个答案:

答案 0 :(得分:14)

您可以使用以下代码示例

    private static DataSet SampleData()
    {
        DataSet sampleDataSet = new DataSet();
        sampleDataSet.Locale = CultureInfo.InvariantCulture;
        DataTable sampleDataTable = sampleDataSet.Tables.Add("SampleData");

        sampleDataTable.Columns.Add("FirstColumn", typeof(string));
        sampleDataTable.Columns.Add("SecondColumn", typeof(string));
        DataRow sampleDataRow;
        for (int i = 1; i <= 49; i++)
        {
            sampleDataRow = sampleDataTable.NewRow();
            sampleDataRow["FirstColumn"] = "Cell1: " + i.ToString(CultureInfo.CurrentCulture);
            sampleDataRow["SecondColumn"] = "Cell2: " + i.ToString(CultureInfo.CurrentCulture);
            sampleDataTable.Rows.Add(sampleDataRow);
        }

        return sampleDataSet;
    }