你的位置:首页 > ASP.net教程

[ASP.net教程]Winform开发 如何为dataGridView 添加CheckBox列,并获取选中行


 

//添加CheckBox列

DataGridViewCheckBoxColumn columncb = new DataGridViewCheckBoxColumn();
columncb.HeaderText = "选择";
columncb.Name = "cb_check";
columncb.TrueValue = true;
columncb.FalseValue = false;
//column9.DataPropertyName = "IsScienceNature";
columncb.DataPropertyName = "IsChecked";
dataGridView1.Columns.Add(columncb);

private void SetAllRowChecked()
{
// DataGridCell cel=(sender as DataGridCell).
int count = Convert.ToInt16(this.dataGridView1.Rows.Count.ToString());
for (int i = 0; i < count; i++)
{
DataGridViewCheckBoxCell checkCell = (DataGridViewCheckBoxCell)dataGridView1.Rows[i].Cells["cb_check"];
Boolean flag = Convert.ToBoolean(checkCell.Value);
if (flag == false) //查找被选择的数据行
{
checkCell.Value = true;
}
continue;
}
}

/// <summary>
/// 表格单元点击事件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
if (e.ColumnIndex==0&&e.RowIndex!=-1)
{
//获取控件的值

DataGridViewCheckBoxCell checkCell=(DataGridViewCheckBoxCell)this.dataGridView1.Rows[e.RowIndex].Cells["cb_check"];
Boolean flag = Convert.ToBoolean(checkCell.Value);
if (flag==true)
{
checkCell.Value = false;
}
else
{
checkCell.Value = true;
}
}
}