datagridview 添加 全选 全消 删除选中行

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace Wind
{
public partial class Form1 : Form
{

int c = 1;

public Form1()
{
InitializeComponent();
}


//全选或取消全选
private void btn_SelectAll(object sender, EventArgs e)
{
int selectedRows = dgv.SelectedRows.Count;
if (selectedRows == dgv.Rows.Count)
{
foreach (DataGridViewRow dr in dgv.SelectedRows)
{
dr.Selected = false;
}
}
else
dgv.SelectAll();
}

//清空所有记录
private void btn_Clear(object sender, EventArgs e)
{
dgv.Rows.Clear();
}

//删除所有选中的行
private void btn_deleteSelectedRows(object sender, EventArgs e)
{
foreach (DataGridViewRow dr in dgv.SelectedRows)
{
if(dr.IsNewRow == false)//如果不是已提交的行,默认情况下在添加一行数据成功后,DataGridView为新建一行作为新数据的插入位置
dgv.Rows.Remove(dr);
}
}

//添加一行新记录
private void btn_addOneRecord_Click(object sender, EventArgs e)
{
DataGridViewRow dr = new DataGridViewRow();
dr.CreateCells(dgv);
dr.Cells[0].Value = "h" + c.ToString();
dr.Cells[1].Value = (c++);
dgv.Rows.Insert(0, dr); //添加的行作为第一行
//dgv.Rows.Add(dr); //添加的行作为最后一行
}
}
}

 

转载于:https://www.cnblogs.com/lanze/archive/2012/03/13/2393667.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是在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控件了。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值