2013-02-06 4 views
0

데이터를 데이터베이스에 저장할 때 오류가 발생합니다. DataAdapter.Fill (ds, "Table")은 nvarchar 데이터 형식을 숫자로 변환하는 동안 오류를 나타내는 SqlException을 발생시킵니다.텍스트 상자에서 데이터베이스에 새 레코드를 추가하는 동안 오류가 발생했습니다.

private void btnSave_Click_1(object sender, EventArgs e) 
{ 
    da = new SqlDataAdapter(); 
    da.SelectCommand = new SqlCommand("select * from Measurement where ID = @ID", con); 
    da.SelectCommand.Parameters.AddWithValue("@ID", txtID.Text); 
    SqlCommandBuilder cb = new SqlCommandBuilder(da); 
    da.Fill(ds, "Measurement"); //(SqlException Unhandled)Error converting data type nvarchar to numeric. 

    if (String.IsNullOrEmpty(txtCellNo.Text.Trim())) 
    { 
     MessageBox.Show("Please enter Cell Number"); 
    } 
    else 
    { 
     try 
     { 
      dr = ds.Tables["Measurement"].Rows[0]; 

      dr["CellNumber"] = txtCellNo.Text.Trim(); 
      dr["FirstName"] = txtFirstName.Text; 
      dr["LastName"] = txtLastName.Text; 
      dr["Shirt"] = txtShirt.Text; 
      dr["Pant"] = txtPant.Text; 
      dr["DueDate"] = txtDueDate.Text; 
      dr["Date"] = txtDate.Text; 

      cb.GetUpdateCommand(); 
      da.Update(ds, "Measurement"); 
     } 
     catch (Exception ex) 
     { 
      MessageBox.Show(ex.Message); 
     } 
    } 
} 
+0

을 나는 더 이상 내 도움을 필요로하지 않는 것 같아요, 많은 전문가들은 지금 문제 @AbZy 질문 : – AbZy

+0

에 대답하는 것은 [ "측정"을] 박사 = ds.Tables을 찾을 수 있습니다. 행 [0]. 행 0에 아무 위치도 없다. 내가 당신의 지시를 따랐다. –

+0

그냥 btnSave_Click_1이라는 메서드로 데이터베이스 작업을 수행하는 것을 보았을 때 눈이 아팠다. –

답변

0

이 줄 :

da.SelectCommand.Parameters.AddWithValue("@ID",txtID.Text); 

txtID.Text 당신이 정수로 변환 할 문자열입니다. Int.TryParse

+0

Int.TryParse charm처럼 작동했습니다! 감사합니다 LarsTech –

0

당신은 (데이터베이스 관점에서 NVARCHAR) 문자열로 데이터베이스에 @ID을 전달하고 있습니다. @ID 명령 매개 변수를 설정할 때 txtID.Text을 적절한 숫자 값으로 변환/변환해야합니다. int.Parse(txtID.Text) (ID는 데이터베이스의 정수라고 가정)에 전화해야한다고 생각합니다.

txtID.Text에 잘못된 ID가 입력되지 않도록주의해야 할 수도 있습니다. 이 시나리오에서는 다음과 같이 사용할 수 있습니다

int id; 
if (!int.TryParse(txtID.Text, out id)) 
{ 
    //an invalid id was supplied so stop processing and warn user 
} 
0

txtID.Text은 정수가 아닐 수 있습니다. 먼저 변환해야합니다. 시도 :

da.SelectCommand.Parameters.AddWithValue("@ID",Convert.ToInt32(txtID.Text)); 
관련 문제