3

I have a DataTable dt whose all columns are of type string but many of them have "interger values" in them but as a string only.

For Example:-

ColA

23

34

56

These are also stored in datatable but as a string value.

I want to know how can I make a clone of my datatable with columns having valid datatype according to the content of that column.

Suresh Kamrushi
  • 15,627
  • 13
  • 75
  • 90
  • 2
    Hi, i ave seen that but there they have done it with only int32, where as i am asking to first get the type and then convert accordingly. –  May 12 '16 at 13:03
  • @PranayDeep get type from what? – SᴇM May 12 '16 at 13:10
  • 1
    You probably need to test each string if they can be converted into other data type, and then creates a table according to the test result – Ian May 12 '16 at 13:19
  • How is the datatable populated? Can you do the conversion there rather than populating _then_ converting? – D Stanley May 12 '16 at 13:32
  • it is populating from an xml. –  May 12 '16 at 13:59

1 Answers1

0

In this case you can use the typeof to enumerate through a list of types and determine what type it is. https://msdn.microsoft.com/en-us/library/58918ffs.aspx

For example you can do something like that:

if (obj1.GetType() == typeof(int)){
    // do something with int
}else if (obj1.GetType() == typeof(string)){
    // do something with string
}

Otherwise if it isn't an object but just a value you can compare with is:

if (myValue is Foo)
    Foo foo = (Foo)myValue;

EDIT: Ok I did a mistake. You have to use tryParse to achieve what you want. The approach is pretty the same, you have to loop through different types and check the return value if the parsing was successful. For example:

int number;

bool result = Int32.TryParse(myString, out number);
if (result)
{
    Console.WriteLine("Converted '{0}' to {1}.", myString, number);         
}
Iamnino
  • 360
  • 1
  • 4
  • 17
  • Oh I see... didn't understand that, sorry. Well there is still a similar solution with the `tryParse`. I'll edit my answer above. – Iamnino May 12 '16 at 13:21