CryptoJones
CryptoJones

Reputation: 745

list Values to dataTable

I created a list from an excel document that has partnumbers on the every other starting with the first, and prices on every other row, starting with the second.

Lets say I initialize a datatable like so..

         DataTable priceListTable = new DataTable();
         priceListTable.Columns.Add("ItemNumber", typeof(string));
         priceListTable.Columns.Add("Price", typeof(Float));

And my list (called recordList) looks this;

001-001
1.45 
001-002
3.49

How do I get the first two rows of the list to fill the columns of the dataTable?

Upvotes: 0

Views: 52

Answers (2)

Ash Burlaczenko
Ash Burlaczenko

Reputation: 25435

Here's one solution.

Loop over the list 2 items at a time starting from the 2nd item. This makes sure you always have a pair of items to use.

for (int i = 1; i < list.Count; i += 2)
{
    DataRow row = table.NewRow();
    row["ItemNumber"] = list[i-1];
    row["Price"] = list[i];

    table.Rows.Add(row);
}

Upvotes: 1

CryptoJones
CryptoJones

Reputation: 745

        string ItemNumber = "ItemNumber";
         string Price = "Price";
         DataTable priceListTable = new DataTable();
         DataRow row;
         priceListTable.Columns.Add(ItemNumber);
         priceListTable.Columns.Add(Price);
         int counter = 0;


        foreach(string s in recordList)
        {
            myTableSize++;
        }



       foreach(string s in recordList)
       {
           if (counter < myTableSize)
           {
               row = priceListTable.NewRow();
               row[ItemNumber] = recordList[counter];
               row[Price] = recordList[counter + 1];
               priceListTable.Rows.Add(row);
               counter++;
               counter++;
           }

Upvotes: 0

Related Questions