0

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?

4
  • You have to create a new column for the age as integer which automatically get placed as last column. You can then move the column to any position. You would also need to copy the data row by row from old age column to new age column. Commented Jun 13, 2022 at 10:50
  • 1
    Why do you have the DataTable age field of string type in first place? Commented Jun 13, 2022 at 11:44
  • Cause I get the DataTable from a diffrent source, that stores it as an string. The DataTabe has to be inserted to an SQL @dr.null Commented Jun 13, 2022 at 12:09
  • Well, for the databases, the same question applies. Fields as such should be of type integer. Right? If you own them then fix this issue to not face problems in future like this one. Data types exist for a reason. Good luck Kazee. Commented Jun 13, 2022 at 12:26

2 Answers 2

4

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)}");
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Since I cant Upvote atm thanks!!!
0

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 column (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 trying 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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.