DataGridView中对各种类型的单元格控件的事件处理(DataGridViewCheckBoxCell、DataGridViewComboBoxCell等的选定、事件触发)

DataGridView控件中的列有多种类型,如表示按钮类型的DataGridViewButtonColumn、表示复选框类型的DataGridViewCheckBoxColumn、表示下拉框类型的DataGridViewComboBoxColumn、表示图片类型的DataGridViewImageColumn、表示超级链接类型的DataGridViewLinkColumn、表示文本框类型的DataGridViewTextBoxColumn。这些列中的单元格的类型又分别为DataGridViewButtonCell、DataGridViewCheckBoxCell、DataGridViewComboBoxCell、DataGridViewImageCell和DataGridViewLinkCell。

这些类型的Column某种程度上可以分别对应WinForm的Button控件、CheckBox控件、PictureBox控件、LinkLabel控件和TextBox控件,但是又有很大的区别,尤其是在事件的处理上,如,当我们用WinForm的CheckBox控件的时候,通过CheckedChanged事件可以很容易得到CheckBox的选定状态,进而进行一些其他控制,但是在DataGridView中的“CheckBox”只能借助于DataGridView的触发事件对“CheckBox”的状态进行间接判断和控制。下面就阐述几种常见的情景:

1)  单击单元格中的Button、Link和CheckBox时进行某些操作,可以利用DataGridView的CellContentClick事件实现该功能。如下面的代码所示:

假设嵌入的DataGridViewButtonCell、DataGridViewLinkCell和DataGridViewCheckBoxCell分别在DataGridView的第一列,第二列和第三列。

private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)

   {

if(e.ColumnIndex==0)

{

MessageBox.Show("你按下了一个按钮!");

}

else if(e.ColumnIndex==1)

{

MessageBox.Show("你单击了一个超级链接!");

}

else if (e.ColumnIndex == 2)

{

       bool b = (bool)this.dataGridView1.Rows[0].Cells[1].EditedFormattedValue;

if (b)//判断CheckBox是否已选中

{

MessageBox.Show("你选定了该CheckBox!");

}

else

{

MessageBox.Show("你使该CheckBox失去了选定!");

}

}

   }

上面有两点注意事项:

a)       首先对e的ColumnIndex进行判断,然后在进行操作;

b)      在获取datagridview中某单元格的值得时候 一定要用 EditedFormattedValue属性,此属性获取的是单元格的当前格式化值,而不考虑该单元格是否处于编辑模式,也不考虑是否已提交该值,而value 和FormattedValue返回的往往是编辑以前的数值(其主要原因是焦点问题,当前单元格失去焦点以后才会将编辑后的值提交),所以一定要用EditedFormattedValue来获取值。

2)选定Combobox的某一项,然后做出对应于选定项的特定操作,可以利用DataGridView的CellEndEdi事件实现该功能。如下面的代码所示:

假设嵌入的DataGridViewCombobxCell在DataGridView的第一列。

private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)

{

if(e.ColumnIndex==2)  

{             

MessageBox.Show("你选定的项为:"+dataGridView1.Rows[e.RowIndex].Cells[2]. EditedFormattedValue.ToString());

     }

}

函数中代码,需要使当前单元格失去焦点以后才会执行,因为失去焦点后才会结束编辑模式。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章