c# - 如何将 ComboBox 文本设置为数据源 (C#) 中不存在的值?

标签 c# winforms combobox

我在表单上有多个下拉式组合框,用户可以在其中指定与值关联的单位(例如米、英尺等)。为此,我在 Settings.Settings 中使用应用程序字符串集合以及一些默认单元类型,这些单元类型绑定(bind)到 ComboBox 的数据源,如下所示:

this.cboUnit.DataSource = 
    (System.Collections.Specialized.StringCollection)Properties.Settings.Default.Units;

用户能够成功选择一个单位或指定一个新单位。

现在,当我将 this.cboUnit.Text 保存到某个 XML 配置文件中时,我能够处理这两种情况。打开 XML 配置文件并执行 this.cboUnit.Text = "NonExistentUnit"; 将失败并导致选择集合中的第一项。

如何修改 ComboBox 以支持我所要求的行为类型,无需将项目添加到 ComboBox 或修改数据源本身

Using ComboBox.Text when combobox is tied to DataSource中建议了一个解决方案但我找不到支持这种行为的官方文档。因此,我宁愿避免它。

最佳答案

我找不到任何有效的方法将项目插入绑定(bind)的数据源。因此,我最终做了以下事情:

BindingSource bindingSource = new BindingSource((System.Collections.Specialized.StringCollection)Properties.Settings.Default.Units, "");
if(!bindingSource.Contains(someSavedValue))
{
    bindingSource.Insert(0, someSavedValue));
}
this.cboUnit.DataSource = bindingSource;

这将创建绑定(bind)源的新实例,可以在将其绑定(bind)到数据源之前对其进行修改。我将此代码包装在一个方法中,我可以为其传递字符串集合和存储值(在本例中为 savedUnit),该值返回新的 BindingSource 实例。这对我来说特别有用,因为我现在可以简单地写:

this.cboLengthUnit.DataSource = CreateBindingSource(unitsCollection, savedLengthUnit);
this.cboWidthUnit.DataSource = CreateBindingSource(unitsCollection, savedWidthUnit);
this.cboHeightUnit.DataSource = CreateBindingSource(unitsCollection, savedHeightUnit);

上面的代码是我凭内存写的,所以可能有错误。

关于c# - 如何将 ComboBox 文本设置为数据源 (C#) 中不存在的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21537571/

相关文章:

c# - AutoMapper IsSourceValueNull 条件不起作用

c# - 当我调用 BeginXXX() 时,CLR 何时创建 IO 线程

c# - 创建表单(没有表单设计器)

python - Python xlwt模块中的Excel组合框

c# - 使用 LINQ to SQL 获取连接结果

c# - C# 中的 System.Linq.Expressions 是干什么用的?

c# - 如何将 DateTimePicker 设置为只读?

vb.net - 使文本适合 VB.net Windows 窗体中的文本框

php mysql 组合框更新不起作用

C#/WPF : Binding Combobox ItemSource in Datagrid to element outside of the DataContext