Google了一下, 原來這個(gè)問題很多人碰到過,也有一些解決方案.不過感覺大多不好,有些許的問題.也許有好的,我沒找到吧.于是在前人基礎(chǔ)上,小小的改動(dòng)了下.
目前還有兩個(gè)小問題待解決:
1) DataGridView最后一行,第一列的ComboBox輸入值,DataGridView應(yīng)該自動(dòng)增加一行(編輯其他列會(huì)自動(dòng)增加一行).
2) 第一列的ComboBox中,假設(shè)其Items中有Shenzhen, 我輸入Shen,Cell中的Value將會(huì)時(shí)Shen. 當(dāng)再次點(diǎn)擊ComboBox,顯示下拉Item時(shí),Item中的Shenzhen會(huì)高亮顯示,ComboBox的Text會(huì)自動(dòng)變成Shenzhen. 其實(shí)這也是ComboxBox的一個(gè)功能.可能有時(shí)不需要這個(gè)功能.
using System;
using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;
//此Form中有兩個(gè)控件,一個(gè)DataGridView(dataGridView1),一個(gè)ComboBox(comboBox1)
//DataGridView中有兩列(都是DataGridViewTextBoxColumn的),其中第一列實(shí)現(xiàn)類似ComboBox的功能
//第一列中只有正在編輯的Cell才會(huì)顯示ComboBox,其他的不會(huì)顯示,這樣好看一點(diǎn)
namespace Test
{
public partial class Form1 : Form
{
private int comboBoxColumnIndex = 0; // DataGridView的首列
public Form1()
{
InitializeComponent();
InitComboBoxValues();
this.dataGridView1.Controls.Add(this.comboBox1);
this.dataGridView1.CellEnter += new DataGridViewCellEventHandler(dataGridView1_CellEnter);
this.dataGridView1.CellLeave+=new DataGridViewCellEventHandler(dataGridView1_CellLeave);
}
private void InitComboBoxValues()
{
this.comboBox1.Items.AddRange(new String[] { "Beijing", "Shanghai", "Guangzhou", "Wuhan", "Shenzhen" });
this.comboBox1.AutoCompleteMode = AutoCompleteMode.Suggest; //輸入提示
this.comboBox1.AutoCompleteSource = AutoCompleteSource.ListItems;
}
private void dataGridView1_CellEnter(object sender, DataGridViewCellEventArgs e)
{
if (e.ColumnIndex == comboBoxColumnIndex)
{
//此處cell即CurrentCell
DataGridViewCell cell = this.dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex];
Rectangle rect = this.dataGridView1.GetCellDisplayRectangle(cell.ColumnIndex, cell.RowIndex, true);
this.comboBox1.Location = rect.Location;
this.comboBox1.Size = rect.Size;
comfirmComboBoxValue(this.comboBox1, (String)cell.Value);
this.comboBox1.Visible = true;
}
}
private void dataGridView1_CellLeave(object sender, DataGridViewCellEventArgs e)
{
if (e.ColumnIndex == comboBoxColumnIndex)
{
//此處cell不為CurrentCell
DataGridViewCell cell = this.dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex];
cell.Value = this.comboBox1.Text;
this.comboBox1.Visible = false;
}
}
private void comfirmComboBoxValue(ComboBox com, String cellValue)
{
com.SelectedIndex = -1;
if (cellValue == null)
{
com.Text = "";
return;
}
com.Text = cellValue;
foreach (Object item in com.Items)
{
if ((String)item == cellValue)
{
com.SelectedItem = item;
}
}
}
}
}