2013-12-11 35 views
0

我有一個包含2列的datagridview。列1可以具有隨機填充的單元格。我想運行一個代碼讀取所有單元格我試過這個代碼在C#中讀取DatagridView中的空單元格#

for (int i = 0; i < (dataGridView1.Rows.Count - 1); i++) 
{ 
    for (int j = 0; j < dataGridView1.Columns.Count; j++) 
    { 
     if (this.dataGridView1.Rows[i].Cells[0] != null 
      && this.dataGridView1.Rows[i].Cells[1] != null) 
     { 
      str1 = this.dataGridView1.Rows[i].Cells[0].Value.ToString(); 
      str2 = this.dataGridView1.Rows[i++].Cells[0].Value.ToString(); 
      if (str1 != str2) 
      {//Some code will be here}` 
      ..... 

但是,循環終止閱讀任何空單元格後...請幫助我。我需要儘快完成這項工作..

回答

0
for (int i = 0; i < (dataGridView1.Rows.Count - 1); i++) 
{ 
if (this.dataGridView1.Rows[i].Cells[0] != null && this.dataGridView1.Rows[i].Cells[1] !=null) 
    { 
    for (int j = 0; j < dataGridView1.Columns.Count; j++) 
    { 
    if(this.dataGridView1.Rows[i].Cells[0].Value != null) 
     { 
    str1 = this.dataGridView1.Rows[i].Cells[0].Value.ToString(); 
     } 
    if(str2 = this.dataGridView1.Rows[i++].Cells[0].Value != null) 
    { 
    str2 = this.dataGridView1.Rows[i++].Cells[0].Value.ToString(); 
    } 
    if (str1 != str2) 
    {//Some code will be here 
    }//if condition end 
    }//if condition end 
    }//for loop end 
}//for loop end 

如果要檢查和你已經檢查空單元格給予任何價值,如果它不爲空那麼只有你可以把它轉換成字符串。如果您嘗試使用.ToString()將空值轉換爲字符串,則會引發異常。

上面的代碼進行修改,請嘗試在網格視圖內容

+0

由於加布裏埃爾去除重複的,我有我的解決方案....感謝 –

+0

使用Convert.toString()來處理的噸的'NULL'並與「」(空字符串) – Pranav

+0

@SuryaKantTripathi比較,如果答案幫助接受/ upvote通常是有幫助的,請閱讀http://meta.stackexchange.com/questions/5234/how-does-accepting-an-答案工作 – mockinterface

相關問題