2012-03-05 4 views
0

C#의 DataGridView에서 null 셀 값을 어떻게 확인할 수 있습니까? 검사를 위해 DBNull을 사용했지만 작동하지 않고 "개체 참조가 개체의 인스턴스로 설정되지 않았습니다."오류가 발생합니다. VS2010을 사용하고 있습니다.DataGridView의 Null 값

아무도 도와 줄 수 있습니까?

DateGridView에는 다음과 같은 속성이 있습니다 이름 : dgTelFax AllowUserToAddRows : 참 AllowUserToDeleteRows :

내가 현재 가지고있는 코드 진정한 : 사전에

  DataSet objDSTelephone = new DataSet(); 
      DataTable objDTTelephone = objDSTelephone.Tables.Add(); 

      string strTelephoneID = ""; 
      string strTelephone = ""; 

      int intRecTel = dgTelFax.Rows.Count; 
      if (intRecTel > 0) 
      { 
       //-- Add columns to the data table 
       objDTTelephone.Columns.Add("id", typeof(string)); 
       objDTTelephone.Columns.Add("telephone", typeof(string)); 

       for (int i2 = 0; i2 <= intRecTel - 1; i2++) 
       { 
        strTelephoneID = (!DBNull.Value.Equals(dgTelFax.Rows[i2].Cells[0].Value)) ? dgTelFax.Rows[i2].Cells[0].Value.ToString() : ""; 
        strTelephone = (!DBNull.Value.Equals(dgTelFax.Rows[i2].Cells[2].Value)) ? dgTelFax.Rows[i2].Cells[2].Value.ToString() : ""; 
        objDTTelephone.Rows.Add(strTelephoneID, strTelephone); 
       } 
      } 

감사합니다!

+0

확인이를 http://stackoverflow.com/questions/3155684/handle-empty-cells-in-datagridview : 셀의 값을 확인하는 get 셀 값 전에 – Raymund

답변

1

이 경우 dgTelFax에는 DBNull.Value가 포함되지 않지만 단순 null이 포함됩니다. 데이터 소스의 열 유형이 문자열 인 경우

strTelephoneID = (dgTelFax.Rows[i2].Cells[0].Value ?? string.Empty).ToString(); 
strTelephone = (dgTelFax.Rows[i2].Cells[2].Value ?? string.Empty).ToString(); 

, 말할 충분하다 :이 테스트하려면 작성합니다

strTelephoneID = (string)dgTelFax.Rows[i2].Cells[0].Value; 
strTelephone = (string)dgTelFax.Rows[i2].Cells[2].Value; 

을하지만 질문은 - 왜 당신이 데이터 그리드를 결합하지 않는다 objDT 텔레폰? 그러면 직접 데이터를 전송할 필요가 없습니다.

if(!string.IsNullOrEmpty(dgTelFax.Rows[2].Cells[0].Value) { 
    strTelephoneID = dgTelFax.Rows[2].Cells[0].Value.Tostring(); 
} 
0