Home > OS >  C# GetDataType from String in DataTable
C# GetDataType from String in DataTable

Time:06-13

I have a DataTable that is populated with only strings at the moment. I want to get from the DataTable Columns the DataType and insert the DataType.

DataTable example, all row names can be random.

enter image description here

And I want to have from the example Column "age" as int, and the rest still string.

At the moment the Age is a string, can I try to Parse the whole column? Or would this be a bad solution.

Is there a simple way to do this?

CodePudding user response:

Sorry if I do not understand your question but I will try to answer what I think you're asking below:

If you're just trying to determine the data type then I would suggest taking the first value in said collumn (as you don't need to check them all obviously.) And do a tryparse to determine if it is compatible with int for example. If you used getType it would likely return a String.

If you're trting to SET the whole column as a data type then you should probably be doing this at the stage you're generating the table via a constructor or programatically as shown in the first example

// Create second column.
column = new DataColumn();
column.DataType = System.Type.GetType("System.String");
column.ColumnName = "ParentItem";
column.AutoIncrement = false;
column.Caption = "ParentItem";
column.ReadOnly = false;
column.Unique = false;
// Add the column to the table.
table.Columns.Add(column);

Full Example from Microsoft

CodePudding user response:

You can not change the data type once the table is loaded. Clone the current DataTable from the original table, find the age column, change data type from string to int then import rows.

Important: The above assumes that, in this case the age column can represent an int on each row, if not you need to perform proper assertion before using ImportRow.

Here is a conceptual example

private static void ChangeColumnType()
{
    DataTable table = new DataTable();

    table.Columns.Add("Seq", typeof(string));
    table.Columns.Add("age", typeof(string));
    table.Columns.Add("name", typeof(string));

    table.Rows.Add("1", "22", "Smith");
    table.Rows.Add("2", "46", "Jones");

    DataTable cloned = table.Clone();
    bool found = false;
    for (int index = 0; index < table.Columns.Count; index  )
    {
        if (string.Equals(table.Columns[index].ColumnName, "age", 
                StringComparison.CurrentCultureIgnoreCase))
        {
            cloned.Columns["age"]!.DataType = typeof(int);
            found = true;
        }
    }

    if (!found) return;
    foreach (DataRow row in table.Rows)
    {
        cloned.ImportRow(row);
    }

    foreach (DataColumn column in cloned.Columns)
    {
        Console.WriteLine($"{column.ColumnName}\t{column.DataType}");
    }


}

Edit: One possible way to avoid issues when age can not be converted to an int.

if (!found) return;
foreach (DataRow row in table.Rows)
{
    if (int.TryParse(row.Field<string>("age"), out _))
    {
        cloned.ImportRow(row);
    }
    else
    {
        Console.WriteLine($"Failed: {string.Join(",", row.ItemArray)}");
    }
}
  • Related