最近一個需求,需要實現在dataGridView的單元格中放入下拉框進行選擇,即放入comboBox控件,整體的思路很簡單,comboBox通過代碼進行初始化。在點擊某個單元格的時候,觸發單元格的事件,然後顯示下拉框,當選擇了數據之後,贏藏comboBox,並將選擇的數據綁定到單元格對應的位置即可。
首先建立一個Winform程序,拖入dataGridView控件。建立窗口的Load事件,編寫一個dataGridView數據初始化方法和一個comboBox初始化的方法,在窗口Load事件中加載這兩個方法。
private void InitComboBox()
{
comboBox = new ComboBox();
this.comboBox.Items.Add("通過");
this.comboBox.Items.Add("未通過");
this.comboBox.Leave += new EventHandler(ComboBox_Leave);
this.comboBox.SelectedIndexChanged += new EventHandler(ComboBox_TextChanged);
this.comboBox.Visible = false;
this.comboBox.DropDownStyle = ComboBoxStyle.DropDownList;
this.dataGridView1.Controls.Add(this.comboBox);
}
private void ShowData()
{
this.dataGridView1.RowCount = 4;
for(int i = 0;i < 4;i++)
{
this.dataGridView1.Rows[i].Cells["Column1"].Value = i;
this.dataGridView1.Rows[i].Cells["Column2"].Value = i+1;
this.dataGridView1.Rows[i].Cells["Column3"].Value = i+2;
this.dataGridView1.Rows[i].Cells["Column4"].Value = "";
}
}
此時數據等已經準備好,接下來是進行點擊單元格顯示comboBox的方法。
在comboBox的初始化中需要添加comboBox的事件,comboBox_TextChanged事件。
private void ComboBox_TextChanged(object sender, EventArgs e)
{
this.dataGridView1.CurrentCell.Value = ((ComboBox)sender).Text;
this.comboBox.Visible = false;
}
再編寫dataGridView的CurrentCellChanged事件:
private void DataGridView1_CurrentCellChanged(object sender, EventArgs e)
{
try
{
if (this.dataGridView1.CurrentCell.ColumnIndex == 3)
{
Rectangle rectangle = dataGridView1.GetCellDisplayRectangle(dataGridView1.CurrentCell.ColumnIndex, dataGridView1.CurrentCell.RowIndex, false);
string value = dataGridView1.CurrentCell.Value.ToString();
this.comboBox.Text = value;
this.comboBox.Left = rectangle.Left;
this.comboBox.Top = rectangle.Top;
this.comboBox.Width = rectangle.Width;
this.comboBox.Height = rectangle.Height;
this.comboBox.Visible = true;
}
else
{
this.comboBox.Visible = false;
}
}
catch(Exception ex)
{
return;
}
}
由於還需要在正常加載時不顯示下拉框,以及選擇完畢之後,隱藏掉下拉框,因此還需要Leave事件以及TextChanged事件:
private void ComboBox_Leave(object sender,EventArgs e)
{
this.comboBox.Visible = false;
}
private void ComboBox_TextChanged(object sender, EventArgs e)
{
this.dataGridView1.CurrentCell.Value = ((ComboBox)sender).Text;
this.comboBox.Visible = false;
}
源碼已上傳,需要的沒有積分的可以聯繫我的郵箱。
資源鏈接:https://download.csdn.net/download/qq_41061437/12046464