最近寫的程序中需要在DataGridView中使用下拉選擇的功能,首選方案是列的ColumnType屬性
使用EditingControlShowing事件,
if (e.Control is ComboBox)
{
int iColumn = dgvWorkerList.CurrentCell.ColumnIndex;
switch (iColumn)
{
case 2://列
{
Gender.DisplayStyle = DataGridViewComboBoxDisplayStyle.DropDownButton;//原來設置的是Nothing
List<string> list = new List<string>();
list.Add("男");
list.Add("女");
Gender.DataSource = list;
(e.Control as ComboBox).SelectedIndexChanged += new EventHandler(ComboBox_SelectedIndexChanged);
}
}
}
由原來的文本轉為下拉框、綁定數據功能完全沒有問題。唯一的問題是
黑色呀,嘗試了強制刷新,無效,懷疑綁定數據問題,測試后覺得不是,因為直接在Items加內容,不使用綁定,結果一樣。
郁悶很久,依然沒有解決。
改方式吧,借鑒了
gldamao 的BLOG
巧用ComboBox控件實現datagridView下拉菜單功能
方法,小修改,實現效果。感謝gldamao。
放一個combox在窗體,Load中
this.cmbGender.Visible = false;
this.cmbGender.Width = 0;
this.dgvWorkerList.Controls.Add(this.cmbGender);
使用CurrentCellChanged事件中判斷
private void dgvWorkerList_CurrentCellChanged(object sender, EventArgs e)
{
try
{
int iIndex = this.dgvWorkerList.CurrentCell.ColumnIndex;
switch (iIndex)
{
case 2:
{
this.cmbGender.Visible = false;
this.cmbGender.Width = 0;
this.cmbGender.Left = this.dgvWorkerList.GetCellDisplayRectangle(this.dgvWorkerList.CurrentCell.ColumnIndex, this.dgvWorkerList.CurrentCell.RowIndex, true).Left;
this.cmbGender.Top = this.dgvWorkerList.GetCellDisplayRectangle(this.dgvWorkerList.CurrentCell.ColumnIndex, this.dgvWorkerList.CurrentCell.RowIndex, true).Top;
this.cmbGender.Width = this.dgvWorkerList.GetCellDisplayRectangle(this.dgvWorkerList.CurrentCell.ColumnIndex, this.dgvWorkerList.CurrentCell.RowIndex, true).Width;
string content = Convert.ToString(this.dgvWorkerList.CurrentCell.Value);
this.cmbGender.Text = content;
this.cmbGender.Visible = true;
List<string> list = new List<string>();
list.Add("男");
list.Add("女");
this.cmbGender.DataSource = list;
}
break;
}
}
}
選列時出現combox添加內容
這里說下,之前用的綁定的方式加入內容,在選擇時候發現無法獲得選中的內容於是修改
for (int i = 0; i < list.Count; i++)
{
this.cmbGender.Items.Add(“男”);
}
之后
private void cmbGender_SelectionChangeCommitted(object sender, EventArgs e)
{
this.dgvWorkerList.CurrentCell.Value = ((System.Windows.Forms.ComboBox)sender).SelectedItem.ToString();
this.cmbGender.Visible = false;//這里稍作修改,選中內容后直接隱藏了combox
this.cmbGender.Width = 0;
}
效果很好。
只是原來的下拉黑色的問題沒有解決,歡迎有辦法的大神留言、指教。