如何在c#数据表中添加列表

本文关键字:添加 列表 数据表 | 更新日期: 2023-09-27 18:07:07

我有多个字符串列表,我想在我的数据表中打印不同列的数据

这是我的代码

List<string> WareHouseStatus = new List<string>();
List<string> Gulf_IT_Barcode = new List<string>();
List<string> Item_Original_SNO = new List<string>();
DataTable NewTempletLaptop_Excel = new DataTable();
NewTempletLaptop_Excel.Columns.Add("WareHouseStatus", typeof(string));
NewTempletLaptop_Excel.Columns.Add("Gulf_IT_Barcode", typeof(string));
NewTempletLaptop_Excel.Columns.Add("Item_Original_SNO", typeof(string));
foreach (var item in WareHouseStatus)
{
    NewTempletLaptop_Excel.Rows.Add(item);
}
foreach (var item in Gulf_IT_Barcode)
{
    NewTempletLaptop_Excel.Rows.Add(item);  ///
}

我的第二个foreach循环添加相同的第一列中的项。

我如何在数据表的所有三列中打印所有这些字符串列表?

如何在c#数据表中添加列表

这不是我想做的最好的设计,但答案是尝试用对原始代码进行最小的更改提出解决方案。

您必须创建所需的行数,然后根据行索引和行列名填充访问的行。

List<string> WareHouseStatus = new List<string>() { "1", "11", "111" };
List<string> Gulf_IT_Barcode = new List<string>() { "2", "22", "222" };
List<string> Item_Original_SNO = new List<string>() { "3", "33", "333" };
System.Data.DataTable NewTempletLaptop_Excel = new System.Data.DataTable();
NewTempletLaptop_Excel.Columns.Add("WareHouseStatus", typeof(string));
NewTempletLaptop_Excel.Columns.Add("Gulf_IT_Barcode", typeof(string));
NewTempletLaptop_Excel.Columns.Add("Item_Original_SNO", typeof(string));
int row = 0; // row index in data
foreach (var item in WareHouseStatus)
{
    // create new row, do it only first time
    NewTempletLaptop_Excel.Rows.Add(NewTempletLaptop_Excel.NewRow());
    // set value to the appropriate cell
    NewTempletLaptop_Excel.Rows[row]["WareHouseStatus"] = item;
    row++;
}
row = 0;
foreach (var item in Gulf_IT_Barcode)
{
    // set value to the appropriate cell
    NewTempletLaptop_Excel.Rows[row]["Gulf_IT_Barcode"] = item;
    row++;
}
row = 0;
foreach (var item in Item_Original_SNO)
{
    // set value to the appropriate cell
    NewTempletLaptop_Excel.Rows[row]["Item_Original_SNO"] = item;
    row++;
}

请注意,如果列表WareHouseStatus比其他列表短,它将失败,因为它的长度定义了DataTable中的行数。您可以添加另一个逻辑来处理这种情况。此外,列名应该在变量中定义一次,这里我对列名进行了"复制-粘贴",只是为了专注于您的问题,并进行了最小的更改,因此它将更加清晰。