我有一个datagridview,它通过从SQL服务器获取数据来填充。
gridview.Datasource = dataSet.Tables[0]
- >没问题。
在此网格中,一列是ComboboxColumn ...
对于这个填充(我的意思是,只绑定一个数据源),没问题:
cmb.DataSource = Enum.GetValues(typeof(MyEnum));
cmb.ValueType = typeof(MyEnum);
cmb.DataPropertyName = "MyEnum";
我想知道数据如何绑定datagridviewcomboboxcolumn(此列的DB中的值是此组合框的选定值的索引。此组合框的数据源是枚举。)
DB中的值:2 - >这是要显示的项目的索引
我可以在某处精确地修改DB列名吗?如果我在datapropertyname中这样做,我会收到错误 - > DataGridViewComboboxCell值无效...
提前致谢!
编辑:问题“已解决”。我用数据表替换了Enum。更简单。
答案 0 :(得分:2)
如上述评论中所述,我向您提供以下选项:
这是一个例子,您可以根据需要对其进行细化,因此首先在设置gridview数据源之前添加未绑定的comboboxColumn为其命名,然后设置datasource,然后设置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);
然后在这两个处理程序中执行此操作(处理CellEndEdit,以便每次编辑包含数据库中的值的单元格时,组合单元也会更新);
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
}