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 设定单元格只读

原文地址:https://www.cnblogs.com/GISRSMAN/p/6023747.html