方法一:
private void dgv_zy_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
int count = Convert.ToInt16(dgv_zy.Rows.Count.ToString());
for (int i = 0; i < count; i++)
{
DataGridViewCheckBoxCell checkCell = (DataGridViewCheckBoxCell)dgv_zy.Rows[i].Cells["cb_check"];
Boolean flag = Convert.ToBoolean(checkCell.Value);
if (flag == true) //查找被選擇的數(shù)據(jù)行
{
checkCell.Value = false;
}
else
continue;
}
}
}
獲取選擇的數(shù)據(jù)
int count = Convert.ToInt32(dgv_zy.Rows.Count.ToString());
for (int i = 0; i < count; i++)
{
//如果DataGridView是可編輯的,將數(shù)據(jù)提交,否則處于編輯狀態(tài)的行無法取到
dgv_zy.EndEdit();
DataGridViewCheckBoxCell checkCell = (DataGridViewCheckBoxCell)dgv_zy.Rows[i].Cells["cb_check"];
Boolean flag = Convert.ToBoolean(checkCell.Value);
if (flag == true) //查找被選擇的數(shù)據(jù)行
{
//從 DATAGRIDVIEW 中獲取數(shù)據(jù)項(xiàng)
string z_zcode = dgv_zy.Rows[i].Cells[0].Value.ToString().Trim();
}
}
方法二:
如果需要在winform 的數(shù)據(jù)控件datagridview 中嵌入checkbox列 ( DataGridViewCheckBoxCell ),
在程序的執(zhí)行中有可能需要像純粹的checkbox控件的selectedindexchanged事件一樣的事件來捕捉其狀態(tài)的改變
我覺得比較好的方式是用datagridview 控件的cellcontentclick事件 例如:
如果嵌入的 DataGridViewCheckBoxCell 列在第一列,判斷狀態(tài)并添加處理事件可以為:
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
if (e.ColumnIndex == 0 && e .RowIndex != -1)
{
//獲取控件的值
MessageBox.Show(this.dataGridView1.Rows[e.RowIndex].Cells[0].EditedFormattedValue.ToString());
//或者可以做其他事件處理程序
}
}
需要注意的是執(zhí)行此事件是需要屏蔽其他datagridview單元格的cellcontentclick事件 ,即讓除了 DataGridViewCheckBoxCell 列
之外的所有列的ReadOnly=True;
在獲取datagridview中checkbox列的值得時(shí)候 一定要用 EditedFormattedValue屬性,此屬性獲取的是編輯以后數(shù)值 而value 和
FormattedValue返回的往往是編輯以前的數(shù)值,而其重復(fù)單擊的時(shí)候往往會(huì)出現(xiàn)錯(cuò)誤(無法確定是編輯前還是編輯后的數(shù)值: 主要
原因是焦點(diǎn)問題,需要先移動(dòng)焦點(diǎn)使datagridview獲取更改后的數(shù)據(jù)在區(qū)獲取他 就沒有問題了,所以以后用去獲取數(shù)據(jù)前先要移出
datagridview中的焦點(diǎn)!!!),所以一定要用EditedFormattedValue來獲取屬性值
聲明:本網(wǎng)頁(yè)內(nèi)容旨在傳播知識(shí),若有侵權(quán)等問題請(qǐng)及時(shí)與本網(wǎng)聯(lián)系,我們將在第一時(shí)間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com