如何更改DataTable类型?

时间:2014-03-06 09:42:35

标签: c# datatable type-conversion decimal

如何克隆DataTable并将其列和行类型更改为decimal

private static DataTable GetDataTabletFromCSVFile(string csv_file_path)
{
    DataTable csvData = new DataTable();
    using (TextFieldParser csvReader = new TextFieldParser(csv_file_path))
    {
        csvReader.SetDelimiters(new string[] { "," });
        csvReader.HasFieldsEnclosedInQuotes = true;
        string[] colFields = csvReader.ReadFields();
        foreach (string column in colFields)
        {
            DataColumn datecolumn = new DataColumn(column);
            datecolumn.AllowDBNull = true;
            csvData.Columns.Add(datecolumn);
            ;
        }
        while (!csvReader.EndOfData)
        {
            string[] fieldData = csvReader.ReadFields();
            //Making empty value as null
            for (int i = 0; i < fieldData.Length; i++)
            {
                if (fieldData[i] == "")
                {
                    fieldData[i] = null;
                }
            }
            csvData.Rows.Add(fieldData);
        }
    }

    return csvData;
} 

3 个答案:

答案 0 :(得分:0)

使用允许类型参数的DataColumn构造函数。

public DataColumn(
    string columnName,
    Type dataType
)

http://msdn.microsoft.com/es-es/library/x1tyd60z(v=vs.110).aspx

因此,如果每列都是十进制类型

foreach (string column in colFields)
    {
        DataColumn datecolumn = new DataColumn(column, typeof(decimal));
        datecolumn.AllowDBNull = true;
        csvData.Columns.Add(datecolumn);
    }

答案 1 :(得分:0)

您可以在创建DataColumn时指定数据类型。如果未明确指定数据类型(如示例中所示),则列的类型为string:

DataColumn datecolumn = new DataColumn(column, typeof(Decimal));

答案 2 :(得分:0)

您必须使用decimal.TryParse将字符串解析为decimal并使用正确的列类型。然后,您可以使用支持可空类型的DataRow.SetField扩展名:

foreach (string column in colFields)
{
    DataColumn datacolumn = new DataColumn(column, typeof(decimal));
    datacolumn.AllowDBNull = true;
    csvData.Columns.Add(datacolumn);
}
while (!csvReader.EndOfData)
{
    string[] fieldData = csvReader.ReadFields();
    DataRow addedRow = csvData.Rows.Add();
    for (int i = 0; i < fieldData.Length; i++)
    {
        decimal value;
        if(decimal.TryParse(fieldData[i].Trim(), out value))
            addedRow.SetField<decimal?>(i, value);
        else
            addedRow.SetField<decimal?>(i, null);
    }
}