Click here to Skip to main content
15,906,569 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
I am retriving data from a csv which is comma separated file and all the columns at the first time are represented as string type. But I want to convert a specific column, when I am retriving the data to int to be available to sort it.
I tried the following when I am loading the rows,
//rows loading
dr = dt.NewRow();
dr.ItemArray = sLine.Split('|');
if (dt.Columns.Contains('ID'))
{ dt.Rows.Add(dr, typeof(int)); }
else
{ dt.Rows.Add(dr); }


But is not working; when I try to sort the datatable using a dataview is still getting it as a string...

Tried this too using a DataView from the DataTable,

DataView dv1 = new DataView(dt);
DataView dv2 = new DataView(dt);
int obj;
for ( int x= 0; x<dt.Rows.Count; x++)
{
  int.TryParse(dv1[x][0].ToString(), out obj);
  int.TryParse(dv2[x][0].ToString(), out obj);
}
dv1.Sort = "ItemNo ASC";
dv2.Sort = "ItemNo DESC";


but if I use MeesageBox.Show(dv1[0][0].ToString()); the data is in string is giving me, 1, 10, 100 an so on instead of 1, 2, 3 ...:confused:
Posted
Updated 13-Oct-10 10:23am
v3
Comments
Sunasara Imdadhusen 12-Oct-10 10:01am    
What is the error?
jalmonte 12-Oct-10 12:32pm    
The error for the section of the code is : 'Input String was not in correct format'

1 solution

When you split the row into strings they are still just strings, even if there is a number in them.

You'll want to define the schema before you add the rows to ensure the data types are correct (MSDN reference[^]).

Defining the schema may also require properly casting the values for your data (IIRC). This means you should likely use int.TryParse[^] to extract the value.

Cheers.
 
Share this answer
 
Comments
jalmonte 12-Oct-10 13:31pm    
Can you show to me a sample code, please? Because what I did not work.
TheyCallMeMrJames 12-Oct-10 15:01pm    
"Input String was not in correct format" means that when you tried to parse the int it failed. Check out the tryparse method I suggested above, as it gives you a fail-case that lets you default in a value (like 0) if you need to.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900