在winform中给GridView加checkbox在按钮点击的时候获取选中的checkbox
dataGridView绑定后
bool[] mark = new bool[this.dataGridView1.Rows.Count]; for (int i = 0; i < mark.Length; i++) { mark[i] = false; } //如果你想那个默认被选中 也把相应的mark[i]改为true;
在dataGridView1_CellContentClick事件中
if (e.ColumnIndex == 0) { mark[e.RowIndex] = !mark[e.RowIndex]; }
在button_Click事件中
for (int i = 0; i < mark.Length; i++) { if (mark[i]) MessageBox.Show(this.dataGridView1.Rows[i].Cells[1].Value.ToString()); }
this.dataGridView1 添加了一个DataGridViewCheckBoxColumn 列
为this.dataGridView1.Rows[0]
Cells[0]为checkboxcolumn
this.dataGridView1.Rows[i].Cells[1]为你绑定的数据
private void GetAllIetmDmodule() { IList<IetmDmodule> IetmDmodulelist = new List<IetmDmodule>(); IIetmDmoduleService IetmDmoduleService = new IetmDmoduleService(); IetmDmodulelist = IetmDmoduleService.GetAllIetmDmodule(); if (IetmDmodulelist != null) { foreach (IetmDmodule dmodule in IetmDmodulelist) { DataGridViewRow dgvRow = new DataGridViewRow(); dgvRow.CreateCells(dataGridView1); dgvRow.Cells[1].Value = dmodule.Subject; dgvRow.Cells[2].Value = ""; dgvRow.Cells[3].Value = dmodule.Creator; dataGridView1.Rows.Add(dgvRow); } mark = new bool[this.dataGridView1.Rows.Count]; for (int i = 0; i < mark.Length; i++) { mark[i] = false; } } }
重新整理了一下.
一,如果数据源中有bool类型的列,在绑定之后会自动以checkbox的形式显示,
如果你的是这种情况,只需要在点击button的时候遍历判断即可.
如果数据源中没有可以采用下列方式添加:
ps:数据源为DataTable
//Add a Column with checkbox at last in the Grid DataColumn dtcCheck = new DataColumn("IsMandatory");//create the data //column object with the name dtcCheck.DataType = System.Type.GetType("System.Boolean");//Set its //data Type dtcCheck.DefaultValue = false;//Set the default value DataTable.Columns.Add(dtcCheck);//Add the above column to the //Data Table
二,数据源中没有,只是在DataGridView中存在.
手动添加为:右键点datagridview,编辑列,添加,设置其类型为datagridviewcheckbox
代码添加如下:
this.dataGridView1.Columns.Insert(0, new DataGridViewCheckBoxColumn()); for (int i = 0; i < this.dataGridView1.Rows.Count; i++) { //为datagridviewcheckbox列赋值 this.dataGridView1.Rows[i].Cells[0].Value = true; }
在DataGridView的CellContentClick事件下写
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e) { //判断点的是否是datagridviewcheckbox列并且不是列头 if (e.ColumnIndex == 0 && e.RowIndex != -1) { //dataGridView1.Rows[e.RowIndex].Cells[0].Value = (bool)dataGridView1.Rows[e.RowIndex].Cells[0].EditedFormattedValue; //两种皆可 dataGridView1.Rows[e.RowIndex].Cells[0].Value = !(bool)dataGridView1.Rows[e.RowIndex].Cells[0].Value; } }
在button的Click事件下:
private void button_Click(object sender, EventArgs e) { for (int i = 0; i < this.dataGridView1.Rows.Count; i++) { if ((bool)this.dataGridView1.Rows[i].Cells[0].Value) MessageBox.Show("选择的是第 " + (i+1).ToString()+" 行"); } }