2014-02-07 2 views
3

이 문제에 대한 올바른 해결책을 찾을 수 없었습니다. 매우 간단하다는 것을 알고 있었지만 잊어 버렸습니다. 내가 작성하는 데 사용자가 필요하지 않은 하나의 텍스트 필드가있는 양식이 있습니다. 데이터베이스에 NULL을 삽입하고 싶습니다. 0은 현재 수행하고 있지 않습니다. 나는 내가 무엇을 놓치고 있는지 확실하지 않다. 텍스트 박스는 taxRateTxt 이름, 나를 위해 내가 현재 가지고 작동하지 않습니다데이터베이스에 삽입시 빈 문자열 설정 null

try 
{ 
    using (SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["AbleCommerce"].ToString())) 
    { 
     cn.Open(); 
     SqlCommand cmd = new SqlCommand(); 
     cmd.Connection = cn; 

     cmd.Parameters.Add(new SqlParameter("@FIPSCountyCode", countyCodeTxt.Text)); 
     cmd.Parameters.Add(new SqlParameter("@StateCode", stateCodeList.SelectedValue)); 
     cmd.Parameters.Add(new SqlParameter("@CountyName", countyNameTxt.Text)); 

     string taxStr = taxRateTxt.Text; 
     //test for an empty string and set it to db null 
     if (taxStr == String.Empty) 
     { 
      taxStr = DBNull.Value; 

     } 

     cmd.Parameters.Add(new SqlParameter("@TaxRate", taxStr)); 

     if (AddBtn.Visible == true) 

      cmd.CommandText = addQuery; 

     if (EditBtn.Visible == true) 
     { 
      cmd.CommandText = editQuery; 
     } 

     cmd.ExecuteNonQuery(); 
     cn.Close(); 
    } 

를 내가 여기 실종 무엇?

+0

열의 기본값이 있습니까? – abhi

+0

귀하의 진술서'taxStr = DBNull.Value;'는 (는) 컴파일 시간 오류를 주어야합니다. – Habib

+0

null을 삽입해야하는 경우 SQL Script 삽입 (해당 필드의 기본값이없는 경우)에서 해당 필드를 생략하면됩니다. 삽입 스크립트를 게시물에 추가 할 수 있습니까? –

답변

18

제거 코드

string taxStr = taxRateTxt.Text; 
//test for an empty string and set it to db null 
if (taxStr == String.Empty) 
{ 
    taxStr = DBNull.Value; 

} 

블록 및이를 수행 할 Convert.DBNull (또는 DBNull.Value)에 통과 한

cmd.Parameters.Add(new SqlParameter("@TaxRate", string.IsNullOrEmpty(taxRateTxt.Text) ? (object)DBNull.Value : taxRateTxt.Text)); 
+0

'DBNull.Value'에서'object' 트릭까지 주조하는 것을 좋아합니다. 많은 시간을 절약합니다 -) –

+0

이것은 나를 위해 일했습니다. 감사! –

관련 문제