如上面的评论所述,我为您提供以下选项:
这是一个示例,您可以根据需要对其进行细化,因此首先在设置gridview数据源之前添加未绑定的comboboxColumn为其命名,然后设置数据源,然后设置datagridview数据源并订阅例如CellEndEdit和像这样的 RowStateChanged 事件:
DataGridViewComboBoxColumn col = new DataGridViewComboBoxColumn();
col.DataSource = Enum.GetValues(typeof(MyEnum));
col.Name = "testcolumn";
int index = dataGridView1.Columns.Add(col);
//"index" is if you want to set properties and so on to this column
//but no need for this example.
//dataGridView1.Columns[index].Name = "testcolumn";
dataGridView1.DataSource = test;
//the 2 event-handlers
dataGridView1.CellEndEdit += new DataGridViewCellEventHandler(dataGridView1_CellEndEdit);
dataGridView1.RowStateChanged += new DataGridViewRowStateChangedEventHandler(dataGridView1_RowStateChanged);
然后在这 2 个处理程序中执行此操作(处理 CellEndEdit,因此每次编辑包含数据库值的单元格时,comboboxcell 也会更新);
void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
//here i use TestCol as a name for the column i want to check
//you replace it with the column you have from the database
//if you didnt change it of course...
if (e.ColumnIndex == dataGridView1.Columns["TestCol"].Index)
{
//and here i assign the value on the current row in the testcolumn column
//thats the combobox column...
dataGridView1.Rows[e.RowIndex].Cells["testcolumn"].Value = (MyEnum)((int)dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value);
}
}
private void dataGridView1_RowStateChanged(object sender, DataGridViewRowStateChangedEventArgs e)
{
//here i assign the initial values to the each cell in the combobox column
//this whole example could be done in other ways but in a nutshell
//it should provide you a good kickstart to play around.
if (e.Row.DataBoundItem != null)
{
e.Row.Cells["testcolumn"].Value = (MyEnum)((int)e.Row.Cells["TestCol"].Value);
}
}
我在这里假设数据库中的列只有数字值,例如 0 或 2 或 5,并且您的枚举必须具有相同数量的值,例如,如果在数据库列中您的值达到最大值 5,那么您的枚举将是这样的,例如:
public enum MyEnum
{
zero,
one,
two,
three,
four,
five
}