我們在使用DatagridView的列樣式的時候很方便,可以設置成comboboxcolumn,textboxcolumn等等樣式,使用起來非常方便,但是,這樣設置的列都採用同一種樣式.對同一列採用多種樣式的,就需要單獨對單元格進行操作了.
具體方法如下:
1.實例化一個定義好的控件:如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.中間有座標位置的轉換
comboBox1.Visible = true;
}
else
comboBox1.Visible = false;
}
4.將combobox的值寫回到單元格
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
dataGridView1.CurrentCell.Value = comboBox1.Text;
}
同樣的方式,可以對同一列的不同單元格綁定不同的控件.