簡體   English   中英

選中DataGridView時選中CheckBox

[英]DataGridView check CheckBox when selected

我有一個帶有CheckBoxDataGridView列,我的問題是,當我選擇它所屬的行時如何自動勾選CheckBox 我已經啟用了DataGridView的全行選擇。

DataGridView具有一個名為SelectionChanged的事件,該事件應在用戶每次SelectionChanged另一行時觸發(從技術上講,如果啟用了多選,則在擴展或減少選擇時也將觸發)。 如果將事件處理程序附加到該事件處理程序,則可以在DGV中獲取當前選定的行,並操作DataGridViewCheckBoxColumn單元格的值。

使用DGV時,大多數時候我都是通過綁定源來處理綁定數據。 通常,我發現處理由bindingsource引發的事件並操縱其綁定列表或基礎模型更為可靠,盡管如果您不使用綁定數據,則此路由將不可用。

我認為這不是解決此問題的最佳方法,但這可能會很好。

樣本用戶界面:

在此處輸入圖片說明

我在datagridview中設置的屬性是:
[MultiSelect = False]
[SelectionMode = FullRowSelect]

在您的datagridview_CellClick Event必須添加以下代碼:

private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
   if (e.RowIndex >= 0)
       this.dataGridView1.Rows[e.RowIndex].Cells["colSelect"].Value = true;
}


如果您打算只單擊一次,則必須應用以下代碼:

private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
   if (e.RowIndex >= 0)
   {
       var count = from hasValue in dataGridView1.Rows.Cast<DataGridViewRow>()
                   where Convert.ToBoolean(hasValue.Cells["colSelect"].Value) == true
                   select hasValue;

       if(count.Count() <= 0)
           this.dataGridView1.Rows[e.RowIndex].Cells["colSelect"].Value = true;
   }
}


其他方式:

private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
   if (e.RowIndex >= 0) 
   {
         foreach (DataGridViewRow row in this.dataGridView1.Rows)
             row.Cells["colSelect"].Value = false;

            this.dataGridView1.Rows[e.RowIndex].Cells["colSelect"].Value = true;
   }

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM