DataGridView 复选框 操作大全

             DataGridViewCheckBoxColumn dtCheck = new DataGridViewCheckBoxColumn();
dtCheck.DataPropertyName = "check";
dtCheck.HeaderText = "";
dataGridView1.Columns.Add(dtCheck);
dataGridView1.DataSource = DataTable;

以上代码 是在DataGridView中添加复选框

  private void chkBox_CheckedChanged(object sender, EventArgs e)
{
if (this.chkBox.Checked == true)
{
for (int i = ; i < dataGridView1.Rows.Count; i++)
{
this.dataGridView1.Rows[i].Cells[].Value = true;
}
}
else
{
for (int i = ; i < dataGridView1.Rows.Count; i++)
{
this.dataGridView1.Rows[i].Cells[].Value = false;
}
} // this.dataGridView1.Rows[i].Cells[0].Value =false; }

以上是一个CheckBox 单击事件 用作于 全选/反选

 DataTable dt = (DataTable)dataGridView1.DataSource;
//使用方法
foreach(DataRow row in dt.Rows)
{
if (row["check"].ToString() == "True")
{
//处理方式
}
}

以上是后台代码操作过程 被选中的CheckBox 自己想怎么处理就怎么写

注:如果需要使复选框不能多选时,将DataGridView 的CellValueChanged事件和CurrentCellDirtyStateChanged事件

 private void dataGridView1_CurrentCellDirtyStateChanged(object sender, EventArgs e)
{
DataGridView dgv = (DataGridView)sender;
if (dgv.IsCurrentCellDirty)
{
dgv.CommitEdit(DataGridViewDataErrorContexts.Commit);
}
}
private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
if (e.ColumnIndex == )
{
DataGridView dgv = (DataGridView)sender;
DataTable dt = (DataTable)dgv.DataSource;
DataGridViewCheckBoxCell checkCell = (DataGridViewCheckBoxCell)dgv.Rows[e.RowIndex].Cells[];
bool value = (Boolean)checkCell.Value;
for (int i = ; i < dt.Rows.Count; i++)
{
DataRow row = dt.Rows[i];
if (i != e.RowIndex && value)
{
row["check"] = false;
}
}
dgv.Invalidate();
}
}

========================================================================================================

dataGridView1中复选框批量选中

1、dataGridView1.SelectionMode = 'FullRowSelect ' // dataGridView1 可以选中整行

2、添加一个contextMenuStrip1 控件    //右键菜单

DataGridView 复选框 操作大全 选择 的name = 'SelectToolStripMenuItem'

3、dataGridView1添加CellMouseDown事件 代码如下

   private void dataGridView1_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)
{
if (e.Button == MouseButtons.Right)
{
if (e.RowIndex >= )
{
//若行已是选中状态就不再进行设置
if (dataGridView1.Rows[e.RowIndex].Selected == false)
{
dataGridView1.ClearSelection();
dataGridView1.Rows[e.RowIndex].Selected = true;
}
//只选中一行时设置活动单元格
if (dataGridView1.SelectedRows.Count == )
{
dataGridView1.CurrentCell = dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex];
}
//弹出操作菜单
contextMenuStrip1.Show(MousePosition.X, MousePosition.Y);
}
}
}

4、添加SelectToolStripMenuItem的Click 事件 代码如下

  private void SelectToolStripMenuItem_Click(object sender, EventArgs e)
{
foreach (var item in this.dataGridView1.SelectedRows)
{
int i = ((System.Windows.Forms.DataGridViewBand)((DataGridViewRow)item)).Index; this.dataGridView1.Rows[i].Cells[].Value = true; }
}

这样 我们就完成批量选中复选框的功能了

上一篇:JS判断客户端是否是iOS或者Android手机移动端(转载)


下一篇:CSS之 relative 特性