datagridview checkbox 全选
时间: 2023-09-07 20:17:47 浏览: 163
以下是在WinForms中使用DataGridView控件实现全选复选框的示例代码:
1. 创建一个DataGridView控件,并为其添加一个名为“Select”的复选框列。
```
DataGridViewCheckBoxColumn selectColumn = new DataGridViewCheckBoxColumn();
selectColumn.HeaderText = "Select";
selectColumn.Name = "Select";
dataGridView1.Columns.Insert(0, selectColumn);
```
2. 在Form_Load事件中,将DataGridView控件的DataSource设置为数据源,并将Select列的默认值设置为false。
```
private void Form1_Load(object sender, EventArgs e)
{
// 绑定数据源
dataGridView1.DataSource = dataSource;
// 将Select列的默认值设置为false
foreach (DataGridViewRow row in dataGridView1.Rows)
{
row.Cells["Select"].Value = false;
}
}
```
3. 实现全选复选框的功能。在Select列的HeaderCell上添加一个CheckBox控件,并在其CheckedChanged事件中设置所有行的Select列的值。
```
private void dataGridView1_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
{
// 在Select列的HeaderCell上添加一个CheckBox控件
if (e.ColumnIndex == 0 && e.RowIndex == -1)
{
e.PaintBackground(e.CellBounds, true);
e.Handled = true;
CheckBox cb = new CheckBox();
cb.Size = new Size(14, 14);
cb.Location = new Point(e.CellBounds.X + 5, e.CellBounds.Y + 3);
cb.CheckedChanged += new EventHandler(cb_CheckedChanged);
dataGridView1.Controls.Add(cb);
}
}
private void cb_CheckedChanged(object sender, EventArgs e)
{
// 设置所有行的Select列的值
foreach (DataGridViewRow row in dataGridView1.Rows)
{
row.Cells["Select"].Value = ((CheckBox)sender).Checked;
}
}
```
这样,就可以实现一个具有全选复选框的DataGridView控件了。
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045021.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![application/x-zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![application/x-zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![application/msword](https://img-home.csdnimg.cn/images/20210720083327.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)