naveed ahmed
naveed ahmed

Reputation: 143

How to add List in datatable C#?

I have multiple list of strings with data that I want to print in my datatable in different columns

Here's my code

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);  ///
}

My second foreach loop adds the item in the same 1st column.

How can I print all these string list in all three columns of the datatable?

Upvotes: 0

Views: 3001

Answers (1)

Rami Yampolsky
Rami Yampolsky

Reputation: 475

It is not the best design I would do, but the answer trying do propose solution with minimal changes to the original code.

You have to create the needed numbers of rows, then populate the rows accessing by row index and row column name.

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++;
}

Be aware that it will fail in case your list WareHouseStatus shorter than the other, as its length defines the rows number in the DataTable. You can add another logic that handles this case. In addition the column names shoud be defined once in variables, here I made "copy-paste" of the column name just to be focused on your questions with minimal changes so it will be more clear.

I hope it helps.

Upvotes: 1

Related Questions