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());
}
}
函數中代碼,需要使當前單元格失去焦點以後纔會執行,因爲失去焦點後纔會結束編輯模式。