2015-11-12 23 views
0

enter image description here我有一個這樣的表。c#從dataGridView打印檢查行的單元

CheckBoxColumn Name ID 
-------------------------- 
    false   John 01 
    true    Peter 02 
    true    Steve 03 

我想只打印標記的單元格行分離。

結果必須是這樣的:

Peter 

        02 
Steve 

        03 

複選框列是「編輯DataGridView的選擇」添加。

我在這裏找到一個類似的解決方案,但不是這樣的。我用它,但效果不好。我想請求幫助以獲得正確的代碼。 我的代碼:

  var allCheckedRows = this.dataGridView1.Rows.Cast<DataGridViewRow>() 
           .Where(row => (bool?)row.Cells[0].Value == true) 
           .ToList(); 
     foreach (var row in allCheckedRows) 
     { 


      e.Graphics.DrawString(dataGridView1.Rows[1].Cells[1].FormattedValue.ToString(),this.dataGridView1.Font, new SolidBrush(this.dataGridView1.ForeColor), new Point(0, 10)); 
      e.Graphics.DrawString(dataGridView1.Rows[1].Cells[2].FormattedValue.ToString(),this.dataGridView1.Font, new SolidBrush(this.dataGridView1.ForeColor), new Point(20, 200)); ; 

      e.Graphics.DrawString(dataGridView1.Rows[2].Cells[1].FormattedValue.ToString(), this.dataGridView1.Font, new SolidBrush(this.dataGridView1.ForeColor), new Point(0, 30)); 
      e.Graphics.DrawString(dataGridView1.Rows[2].Cells[2].FormattedValue.ToString(), this.dataGridView1.Font, new SolidBrush(this.dataGridView1.ForeColor), new Point(20, 230)); ;  
     } 

現在的結果讓所有的時間只有第一排和第二排不檢查行。

任何人都可以幫助我得到正確的結果嗎?

Thx提前!

我認爲它可以與「檢查狀態」檢查。

結果必須是!

回答

1

你迭代allCheckedRows但隨後而不是使用rowforeach你打電話dataGridView1.Rows[1]dataGridView1.Rows[2](第二排和第三排)內。 另外,您應該有一個變量來增加繪製的高度,以便不會將所有記錄繪製在彼此之上。 在您的代碼中,您將爲每個選中的列重複繪製第二行和第三行。

這裏是一個可能的解決方案:

  int height = 0; 
      foreach (var row in dataGridView1.Rows) 
      { 
       DataGridViewRow checkedRow = row as DataGridViewRow; 
       if (checkedRow == null || (bool)checkedRow.Cells[0].Value == false) continue; //Skip the row if it's not checked 
       height += 10; 
       e.Graphics.DrawString(checkedRow.Cells[1].FormattedValue.ToString(), this.dataGridView1.Font, new SolidBrush(this.dataGridView1.ForeColor), new Point(0, height)); 

       height += 190; 
       e.Graphics.DrawString(checkedRow.Cells[2].FormattedValue.ToString(), this.dataGridView1.Font, new SolidBrush(this.dataGridView1.ForeColor), new Point(20, height)); 
      } 
+0

如果你有空例外然後進行調試,看看空的來源。 – tzachs

+0

http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it – tzachs

+1

因此,將該行更改爲'if(checkedRow == null ||(bool? )checkedRow.Cells [0] .Value!= true)continue; //如果沒有選中,則跳過該行並檢查它是否有效。 – tzachs