首页 > 解决方案 > How to convert data type items?

问题描述

I have a data table which has 12 items, I need to change the data type of 1st and 10th column

 DataTable dtExcel = null;
dtExcel = GetExcelContainerFor<TBL_TICKETING_ALTERNATE_CREDIT_CARD_LIST>().ImportFromExcel(excelInput.DataVaultFileName, excelInput.IsHeaderRowExists);

so dtExcel is the data table which has the 12 items

I am looping through each data row and trying to convert it to Int32

dtExcel.Select().ToList().ForEach(dataRow =>
                        {
                            dataRow[0] = (Convert.ToInt32(dataRow[0]));
                            dataRow[9] = (Convert.ToInt32(dataRow[9]));
                            
                        });

but as soon as the loops ends , the dtExcel data table has it's original data types.

I tried below coding as well but it didn't work as well(since it threw error as connot convert the datatype)

DataTable newTable = dtExcel.Clone();
                        for (int i = 0; i < dtExcel.Rows.Count; i++)
                        {
                            DataRow drNew = newTable.NewRow();
                            newTable.Columns[0].DataType = typeof(Int32);
                            newTable.Columns[9].DataType = typeof(Int32);
                            drNew.ItemArray = dtExcel.Rows[i].ItemArray;
                            newTable.Rows.Add(drNew);

}

How can I solve this issue? Do I need to create a new datable and loop through each items and then convert each and add?- if yes- can somebody share an example of how to achieve it?

标签: c#loopsdatatablecasting

解决方案


推荐阅读