簡體   English   中英

如何通過復選框啟用和禁用DataGridView中的特定行?

[英]How to enable and disable particular row in DataGridView by checkbox?

我試圖通過選中和取消選中gridview內的復選框來啟用和禁用DataGridView中的特定行。 (C#Windows應用程序)

我嘗試使用無法正常工作的CellClick事件。

這是我嘗試過的代碼

private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
    if (e.ColumnIndex == 0 && dataGridView1.CurrentCell.Selected == true)
    {

        dataGridView1.Columns[3].ReadOnly = false;

    }

}

請告訴我該怎么做。

提前致謝

我認為您錯過了CellContentClick事件,請嘗試以下操作:

private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{          
     if (e.ColumnIndex == dataGridView1.Columns["Your Column Name"].Index) //To check that we are in the right column
     {
          dataGridView1.EndEdit();  //Stop editing of cell.
          if ((bool)dataGridView1.Rows[e.RowIndex].Cells["Your Column Name"].Value)
          {
             //dataGridView1.Columns[3].ReadOnly = true;// for entire column 
               int colIndex = e.ColumnIndex;
               int rowIndex = e.RowIndex;
               dataGridView1.Rows[colIndex].Cells[rowIndex].ReadOnly = true;
          }
    }
}

您可以簡單地使用dataGridView“ CellContentClick”事件。 該代碼如下。

private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
    var _dataGrid = (DataGridView)sender;

    //Give your checkbox column Index
    int chkBoxColumnIndex = 1;

    if (e.ColumnIndex == chkBoxColumnIndex && e.RowIndex >= 0)
    {
        bool isChecked = _dataGrid[chkBoxColumnIndex, e.RowIndex].Value == null ? false : (bool)_dataGrid[chkBoxColumnIndex, e.RowIndex].Value;
        for (int i = 0; i < dataGridView1.Columns.Count; i++)
        {
            _dataGrid[i, e.RowIndex].ReadOnly = isChecked;
        }
    }
}

好吧,您正在將readonly屬性設置為false,這意味着它不是只讀的。 嘗試將其設置為true。 引發此事件的事件也應該是復選框單擊事件(雙擊復選框以創建事件處理程序)。

private void checkBox1_CheckedChanged(object sender, EventArgs e)
{
    dataGridView1.Columns[3].ReadOnly = true;
}

另外,看看凍結的屬性。

dataGridView1.Columns[3].Frozen = true; 

暫無
暫無

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

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