Reputation: 11
I need to parse a string from a datatable into a double. I have a datatable (dt) and it has different columns, and each of these columns are converted to strings with the .ToString()
method. However, when I try to output the latitude and longitude of the data, I get an error "Input string was not in a correct format." So I guess my main question is, how do you parse text from an object converted to a string using the .ToString()
method..
using System;
using System.IO;
using System.Collections;
using System.Data;
namespace SalesMap
{
class SalesMap
{
private static DataTable InitData1()
{
//Datatable for entire list of zipcodes
DataTable datat = new DataTable("DATA");
DataColumn state = new DataColumn();
DataColumn county = new DataColumn();
DataColumn statecounty = new DataColumn();
DataColumn latitude = new DataColumn();
DataColumn longitude = new DataColumn();
DataColumn salesperson = new DataColumn();
//Add the columns to the datatable
datat.Columns.Add(state);
datat.Columns.Add(county);
datat.Columns.Add(statecounty);
datat.Columns.Add(latitude);
datat.Columns.Add(longitude);
datat.Columns.Add(salesperson);
return datat;
}
private static String InitPath()
{
string path = "C:/Documents and Settings/Andre/Desktop/salesmapdata/MapPointCountyLatLong.csv";
return path;
}
public static void Main()
{
try
{
DataTable dt = InitData1();
StreamReader sr = new StreamReader(InitPath());
String csvData = string.Empty;
while ((csvData = sr.ReadLine()) != null)
{
String[] data = csvData.Split(',');
//dt.Rows.Add(data);
DataRow newRow1 = dt.NewRow();
newRow1[0] = data[0].ToString(); //state
newRow1[1] = data[1].ToString(); //county
newRow1[2] = data[2].ToString(); //state|county
newRow1[3] = data[3].ToString(); //latitude
newRow1[4] = data[4].ToString(); //longitude
newRow1[5] = data[5].ToString(); //salesperson
dt.Rows.Add(newRow1);
Console.WriteLine("Row added for: dt");
}
foreach (DataRow row1 in dt.Rows)
{
double latitude1 = Double.Parse(row1[3].ToString());
double longitude1 = Double.Parse(row1[4].ToString());
if (row1[5].ToString() != "UNKNOWN" || row1[5].ToString() != "SALESMAN")
{
Console.WriteLine(latitude1);
Console.WriteLine(longitude1);
}
}
dt.WriteXml(@"c:\test\dt1.xml");
sr.Close();
}
catch (Exception e)
{
StreamWriter sw = new StreamWriter(@"c:\test\error.txt");
sw.WriteLine(e.Message.ToString());
sw.Close();
}
}
}
}
Upvotes: 0
Views: 1046
Reputation: 12128
First of all, when reading data from CSV file, you don't need to call data[x].ToString()
on each array element, since they are already strings.
Few potential issues you might have with Double.Parse calls:
string.IsNullOrWhitespace()
or something similar.Decimal.Parse()
that accepts Culture as parameter (you could supply CultureInfo.InvariantCulture
or any other CultureInfo
).Upvotes: 2