2013-06-17 6 views
0

northwind db에서 뷰의 webgrid를 통해 표시 할 데이터 세트를 검색했습니다. 그러나 고객 개체를 인스턴스화 할 때 'id'필드를 int 값으로 변환 할 때 오류가 발생합니다. 다음 목록은 컨트롤러 파일의 맨 위에 선언DataSet 문자열을 정수로 변환 할 때의 문제

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); 
    } 

내 코드는 ...입니다 ... 나는이 문제를 해결하지만 foreach는 id = int.Parse(dr[0].ToString()) 내부에 여러 가지 방법을했습니다 그러나

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

항상 오류가 있지만 ID를 사용하지 않으면 정상적으로 실행됩니다. 여기

는 ... 오류 메시지입니다

[FormatException을 :. 입력 문자열이 올바른 형식이 아니었다] System.Number.StringToNumber (문자열 str을, NumberStyles 옵션 NumberBuffer & 번호,하는 NumberFormatInfo 정보 , 부울 parseDecimal) +10726387 System.Number.ParseInt32 (String s, NumberStyles 스타일, NumberFormatInfo 정보) +145 System.Int32.Parse (String s) +23
의 Movie.Controllers.HelloController.List() c : \ Users \ peter_000 \ Documents \ Visual Studio 2012 \ Projects \ Movie \ Movie \ Controllers \ HelloCo ntroller.cs 52
lambda_method는 +101

목적은 웹 서비스에 대한 모든 이것을 이동 서비스로 호출한다 (폐쇄가 ControllerBase는 [] 오브젝트). 이것은 아마 사소한해야하지만 내 길을 찾은 것 같습니다.

누구나이 방법을 권유하거나 제안 할 수 있습니까?

+0

'dr [0]'에는 무엇이 들어 있습니까? 디버거를 사용하여 값을 확인 했습니까? – nmat

+0

id = dr [0]처럼 ToString()을 사용하지 않고 시도 했습니까? 아니면 int.TryParse (dr [0] .ToString(), out id)를 사용할 수 있습니까? – Edper

+0

나는 시도의이 첫번째 클립 한 쌍을 시도했다, 아래 해결책은 저를 위해 잘 일했다. 귀하의 의견을 주셔서 감사합니다 –

답변

3

왜 처음부터 문자열로 변환하고 있습니까? 물론

// 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] 
}); 

는 64 비트 정수의 경우는, long (등)에 캐스팅 : 그것을 가정하면 바로 캐스팅 실제로int 유형입니다.

ToString 메서드를 노출하는 모든 것이 기회가 될 때마다 전화를 걸도록 초대해서는 안되기 때문에 가능하면 문자열 변환을 피하십시오.

+0

잘 일하고, 팁 덕분에 존 –

관련 문제