我們在使用DatagridView的列樣式的時候很方便,可以設(shè)置成comboboxcolumn,textboxcolumn等等樣式,使用起來非常方便,但是,這樣設(shè)置的列都采用同一種樣式.對同一列采用多種樣式的,就需要單獨(dú)對單元格進(jìn)行操作了.
具體方法如下:
1.實(shí)例化一個定義好的控件:如combobox
2.初始化combobox控件
3.獲取
private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
if (dataGridView1.CurrentCell.ReadOnly == false && dataGridView1.CurrentCell.RowIndex == 2) // combobox顯示條件
{
comboBox1.Text = dataGridView1.CurrentCell.Value.ToString(); //對combobox賦值
R = dataGridView1.GetCellDisplayRectangle(dataGridView1.CurrentCell.ColumnIndex, dataGridView1.CurrentCell.RowIndex, false); //獲取單元格位置
comboBox1.SetBounds(R.X + dataGridView1.Location.X, R.Y + dataGridView1.Location.Y, R.Width, R.Height); //重新定位combobox.中間有坐標(biāo)位置的轉(zhuǎn)換
comboBox1.Visible = true;
}
else
comboBox1.Visible = false;
}
4.將combobox的值寫回到單元格
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
dataGridView1.CurrentCell.Value = comboBox1.Text;
}