dataGridView設置行列不可用 失效問題


想起一件小技巧,記錄下。

 

0.設置不可編輯的幾種方式

第一種方式,一般使用ReadOnly=true屬性設置。

第二種方式,使用EditMode 屬性:DataGridView.EditMode 屬性被設置為 DataGridViewEditMode.EditProgrammatically 時,用戶就不能手動編輯單元格的內容了。但是可以通過程序,調用 DataGridView.BeginEdit 方法,使單元格進入編輯模式進行編輯。

第三種方式:根據條件設定單元格的不可編輯狀態

當一個一個的通過單元格坐標設定單元格 ReadOnly 屬性的方法太麻煩的時候,你可以通過 CellBeginEdit 事件來取消單元格的編輯。

// CellBeginEdit 事件處理方法
private void DataGridView1_CellBeginEdit(object sender,
    DataGridViewCellCancelEventArgs e)
{
    DataGridView dgv = (DataGridView)sender;
    //是否可以進行編輯的條件檢查
    if (dgv.Columns[e.ColumnIndex].Name == "Column1" &&
        !(bool)dgv["Column2", e.RowIndex].Value)
    {
        // 取消編輯
        e.Cancel = true;
    }
}

 

1.設置行只讀

DataGridView是使用時設置某些行不可用時ReadOnly會發現失效,仍然可以編輯。

  dataGridView.DataSource = DataTable0;
  //此時設置失效
  dataGridView.Rows[0].ReadOnly = true;

可能在於數據刷新后這個設置即無效,例如重新綁定、切換tab等事件發生。

 

實際上應該在數據綁定后才可以其效果,即事件DataBindingComplete

        private void dataGridView_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
        {
            //綁定事件DataBindingComplete 之后設置才有效果
            dataGridView.Rows[0].ReadOnly = true;
            //背景設置灰色只讀
            dataGridView.Rows[1].DefaultCellStyle.BackColor = Color.Lavender;
            
            //同樣 Style設置最好也在綁定事件后
            //dataGridView.Rows[0].HeaderCell.Style = style;
        }

 

2.設置列只讀:

 dataGridView.Columns("列名").ReadOnly = True   //設置列只讀  
 dataGridView.Columns("列名").CellTemplate.Style.BackColor = Color.Lavender  //背景設置灰色只讀  

 

3.設置某行某列只讀

 int columnIndex = 0;
 int rowIndex = 0;
 //指定列序號、行序號方式
 dataGridView1[columnIndex, rowIndex].ReadOnly = true;
 //或者這樣寫 按照row的cell
 dataGridView1.Rows[rowIndex].Cells[columnIndex].ReadOnly = true;

 

4.所有單元格不可編輯

DataGridView 內所有單元格都不可編輯(不可新增行,不可刪除行):
dataGridView1.ReadOnly=true;

 

其他:

不顯示最下面的新行:DataGridView1.AllowUserToAddRows = False

是不是最新行:DataGridView1.CurrentRow.IsNewRow

最新行行號:DataGridView.NewRowIndex

禁止DataGridView1的行刪除操作:DataGridView1.AllowUserToDeleteRows = false;

。。。。

其他參見參考鏈接

 

參考:

WinForm設置DataGridView某些行和列只讀

DataGridView 設定單元格只讀


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM