C# Winform中DataGridView的DataGridViewCheckBoxColumn使用方法

下面介绍Winform中DataGridView的DataGridViewCheckBoxColumn使用方法:

 

DataGridViewCheckBoxColumn CheckBox是否选中

   在判断DataGridView中CheckBox选中列的时候,用 DataGridViewRow.Cells[0].FormattedValue.ToString()=="True"语句时存在问题,当我们直接点 击CheckBox时,结果显示未选中,但是如果我们在点击其他单元格时,结果显示选中。而用 DataGridViewRow.Cells[0].EditedFormattedValue.ToString()=="True"语句时不管怎么样 是选中的状态。

为什么会有这种结果?

  原因:就是FormattedValue是操作提交后的结果,而EditedFormattedValue是当前的结果,不管结果是否已经提交。

     所以用DataGridViewRow.Cells[0].EditedFormattedValue.ToString()=="True"判断选中比较合适

 

DataGridViewCheckBoxColumn 设置CheckBox默认选中

   ((DataGridViewCheckBoxCell)dgvDownloadList.Rows[i].Cells["Column1"]).Value = true;

 

DataGridViewCheckBoxColumn 第一时间获取CheckBox的选中状态

  当点击或者取消datagridview的checkbox列时,比较难获得其状态是选中还是未选中,进而不好进行其它操作,下面就列出它的解决办法: 

  CommitEdit :将当前单元格中的更改提交到数据缓存,但不结束编辑模式 

### 动态添加C# WinForms DataGridView 控件 在 C# WinForms 中,可以通过编程方式向 `DataGridView` 添加。以下是实现此功能的一个完整示例: #### 创建并添加 通过创建一个新的 `DataGridViewTextBoxColumn` 或其他类型的(如 `DataGridViewCheckBoxColumn`),可以将其添加到 `DataGridView.Columns` 集合中。 ```csharp // 创建一个新的文本 DataGridViewTextBoxColumn column = new DataGridViewTextBoxColumn(); column.Name = "NewColumnName"; // 设置名 column.HeaderText = "Header Text"; // 设置显示的表头文字 column.DataPropertyName = "PropertyBinding"; // 如果绑定数据源,则设置属性名称 dataGridView1.Columns.Add(column); // 将新添加到 DataGridView ``` 如果需要动态调整样式或其他特性,可以根据引用中的描述进行操作[^3]。例如,定义统一的单元格样式以提高效率。 #### 定义单元格样式 为了优化性能,建议共享同一个 `DataGridViewCellStyle` 对象而不是为每个单元格单独创建样式对象。 ```csharp // 创建一个通用的单元格样式 DataGridViewCellStyle style = new DataGridViewCellStyle(); style.BackColor = Color.LightGray; // 背景色 style.ForeColor = Color.DarkBlue; // 前景色 style.Font = new Font("Arial", 10, FontStyle.Bold); // 字体 // 应用样式到特定 dataGridView1.Columns["NewColumnName"].DefaultCellStyle = style; ``` 以上方法能够有效减少内存消耗和提升渲染速度。 #### 处理事件 当需要处理某些交互行为时,比如检测错误输入或响应用户动作,可利用事件机制完成逻辑控制。例如,在单元格验证失败时记录位置信息。 ```csharp private void dataGridView1_CellValidating(object sender, DataGridViewCellValidatingEventArgs e) { if (string.IsNullOrEmpty(e.FormattedValue.ToString())) { dataGridView1.Rows[e.RowIndex].ErrorText = "This field cannot be empty."; // 记录发生错误的位置 Point cellInError = new Point(e.ColumnIndex, e.RowIndex); } } ``` 上述代码片段展示了如何捕获无效输入的情况,并标记相应的行作为错误状态[^2]。 --- ###
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值