2011-10-20 42 views
0

我想有一個複選框列,當用戶點擊它們,他們選擇自己的行(hightlight它)。我已經提出了這個代碼,並沒有完成這項工作,我該如何解決它?Datagrid複選框列選擇不工作正確

有沒有更好的方法來做到這一點? (即使在「取消選中」複選框後,該行仍保持高亮顯示)。

private void dataGrid_CellClick(object sender, DataGridViewCellEventArgs e) 
     { 
      if (e.ColumnIndex == 0 && e.RowIndex != -1) 
      { 
       if (Convert.ToBoolean(dataGrid.Rows[e.RowIndex].Cells[0].Value) == true) 
        dataGrid.Rows[e.RowIndex].Selected = false; 
       else if (Convert.ToBoolean(dataGrid.Rows[e.RowIndex].Cells[0].Value) == false) 
        dataGrid.Rows[e.RowIndex].Selected = true; 
      } 
     } 

回答

0

CellMouseUp不適用於SPACE印刷機的選擇。
如果你沒有做「實」的選擇,我會改變對細胞值更改行的背景色,這將會是非常容易:

private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e) 
{ 
    if (e.ColumnIndex == 0 && e.RowIndex != -1) 
    { 
     if (Convert.ToBoolean(dataGridView1.Rows[e.RowIndex].Cells[0].Value) == true) 
      dataGridView1.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.Blue; 
     else if (Convert.ToBoolean(dataGridView1.Rows[e.RowIndex].Cells[0].Value) == false) 
      dataGridView1.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.White; 
    } 
} 
1

嘗試將所述邏輯在CellMouseUp事件處理程序作爲該複選框狀態已被更新前的CellClick事件正在發生。

這與使用EditedFormattedValue屬性(其中包含單元格的當前格式化值)一起檢索CheckBoxes當前狀態。

MSDN

Value屬性是由該細胞包含的實際數據對象, 而FormattedValue的是此 對象的格式化表示。

它存儲單元格的當前格式化值,無論 單元格是否處於編輯模式且該值未提交。

這是一個工作示例。

void dataGrid_CellMouseUp(object sender, DataGridViewCellMouseEventArgs e) 
{ 
    if (e.ColumnIndex == 0 && e.RowIndex != -1) 
    { 
     DataGridViewCheckBoxCell checkBoxCell = 
      dataGrid.Rows[e.RowIndex].Cells[0] as DataGridViewCheckBoxCell; 

     if (checkBoxCell != null) 
     { 
      dataGrid.Rows[e.RowIndex].Selected = Convert.ToBoolean(checkBoxCell.EditedFormattedValue); 
     } 
    } 
} 

希望這會有所幫助。

+0

謝謝,它的工作原理,但我想也是其他選中的行保持選中狀態,我該怎麼做? – funerr