如何在c#中编辑数据绑定组合框
本文关键字:数据绑定 组合 编辑 | 更新日期: 2023-09-27 18:29:49
在我的winForm应用程序中,我在数据网格视图中添加了数据绑定的组合框列。用户需要能够从下拉列表中选择一个项目或在组合框中写入。但它不允许我在设置数据源时在组合框中进行编写。这是我的代码:
var entityModel= new AdminEntities();
var filterPractice = (from b in entityModel.FILTER where b.PRACTICE != null select b.PRACTICE).Distinct().OrderBy(y => y);
dgvCboColumn(filterPractice, "PRACTICE");
private void dgvCboColumn(dynamic item, string colName)
{
int i = dgvLoadTable.Columns[colName].Index;
DataGridViewComboBoxColumn dgvCol = new DataGridViewComboBoxColumn();
dgvCol.DataSource=item;
dgvCol.DataPropertyName = colName;
dgvLoadTable.Columns.Insert(i, dgvCol);
dgvLoadTable.Columns[i].HeaderText = dgvLoadTable.Columns[i + 1].HeaderText;
dgvLoadTable.Columns[i + 1].Visible = false;
dgvLoadTable.Columns.RemoveAt(i + 1);
}
private void HandleEditShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
var cbo = e.Control as ComboBox;
if (cbo == null)
{
return;
}
cbo.DropDownStyle = ComboBoxStyle.DropDown;
cbo.Validating -= HandleComboBoxValidating;
cbo.Validating += HandleComboBoxValidating;
}
private void HandleComboBoxValidating(object sender, CancelEventArgs e)
{
var combo = sender as DataGridViewComboBoxEditingControl;
if (combo == null)
{
return;
}
if (!combo.Items.Contains(combo.Text))
{
var comboColumn = this.dgvLoadTable.Columns[this.dgvLoadTable.CurrentCell.ColumnIndex] as DataGridViewComboBoxColumn;
combo.Items.Add(combo.Text);
comboColumn.Items.Add(combo.Text);
this.dgvLoadTable.CurrentCell.Value = combo.Text;
}
}
有人能告诉我如何使组合框可编辑吗?
您可以使用Oledb或Ado记录集手动获取项目frm数据源,并使用for循环手动填充组合框。。所以基本上你也可以编辑项目。。