Peter Donoghue
Peter Donoghue

Reputation: 161

Problems converting DataSet string to Integer

I've retrieved a dataset from the northwind db with a view to displaying out via a webgrid in the view. However when I instantiate the customer object it errors at converting the 'id' field to an int value. Here is my code...

    public ActionResult List()
    {
        SqlConnection conn;
        SqlDataAdapter myDataAdapter;
        DataSet myDataSet;

        string cmdString = "SELECT CustomerID, CompanyName, ContactName, ContactTitle FROM Customers";

        conn = new SqlConnection("Data Source=PETERPC\\SQLEXPRESS;Initial Catalog=Northwind;Integrated Security=True");
        myDataAdapter = new SqlDataAdapter(cmdString, conn);

        myDataSet = new DataSet();
        myDataAdapter.Fill(myDataSet, "Customers");

        foreach (DataRow dr in myDataSet.Tables[0].Rows)
        {
            customers.Add(new Customer() { id = int.Parse(dr[0].ToString()), co_name = dr[1].ToString(), name = dr[2].ToString(), title = dr[3].ToString() });
        }



        return View(customers);
    }

The list declared at the top of the controller file...

private List<Customer> customers = new List<Customer>();

However I've a number of ways around this but inside the foreach the id = int.Parse(dr[0].ToString()) always errors, it will run fine if I don't use the ID however.

Here is the error message...

[FormatException: Input string was not in a correct format.] System.Number.StringToNumber(String str, NumberStyles options, NumberBuffer& number, NumberFormatInfo info, Boolean parseDecimal) +10726387 System.Number.ParseInt32(String s, NumberStyles style, NumberFormatInfo info) +145 System.Int32.Parse(String s) +23
Movie.Controllers.HelloController.List() in c:\Users\peter_000\Documents\Visual Studio 2012\Projects\Movie\Movie\Controllers\HelloController.cs:52
lambda_method(Closure , ControllerBase , Object[] ) +101

The objective is to move all this out to a webservice and call it as a service. This should probably be trivial but I cant seem to find my way round it.

Can anyone advise or suggest a better way of doing this?

Upvotes: 0

Views: 924

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1503579

Why are you converting it to a string in the first place? Assuming it's actually an int type, just cast:

// Property names changed to be more sensible
customers.Add(new Customer {
    Id = (int) dr[0],
    CompanyName = (string) dr[1],
    ContactName = (string) dr[2],
    Title = (string) dr[3]
});

Of course if it's a 64-bit integer, cast it to long (etc).

Avoid string conversions wherever possible - just because everything exposes a ToString method shouldn't be viewed as an invitation to call it at every opportunity.

Upvotes: 3

Related Questions