![](/img/trans.png)
[英]How do I set the text value of a ComboBox to the output of a function in C#?
[英]How can I set ComboBox text to a value not in DataSource (C#)?
我在窗体上具有多个DropDown样式的ComboBox,用户可以在其中指定与值(例如,米,英尺等)关联的单位。 为此,我在Settings.Settings中使用一个应用程序字符串集合,并将其与一些默认单位类型绑定到ComboBox的DataSource,如下所示:
this.cboUnit.DataSource =
(System.Collections.Specialized.StringCollection)Properties.Settings.Default.Units;
用户能够成功选择一个单位或指定一个新单位。
现在,当我将this.cboUnit.Text
保存到某些XML配置文件中时,我能够处理两种情况。 打开XML配置文件并执行this.cboUnit.Text = "NonExistentUnit";
将失败,并导致选择集合中的第一项。
如何在不将项目添加到ComboBox或修改DataSource本身的情况下修改ComboBox以支持我要求的行为?
当combobox绑定到DataSource时,在Using ComboBox.Text中提出了一个解决方案,但我找不到支持此行为的官方文档。 因此,我宁愿避免这种情况。
我找不到将项目插入绑定的DataSource中的任何有效方法。 因此,我最终做了以下工作:
BindingSource bindingSource = new BindingSource((System.Collections.Specialized.StringCollection)Properties.Settings.Default.Units, "");
if(!bindingSource.Contains(someSavedValue))
{
bindingSource.Insert(0, someSavedValue));
}
this.cboUnit.DataSource = bindingSource;
这将创建绑定源的新实例,可以在将其绑定到数据源之前对其进行修改。 我将此代码包装在一个方法中,该方法可以传递一个字符串集合和一个存储的值(在本例中为savedUnit
),该值返回一个新的BindingSource实例。 这对我来说特别有用,因为我现在可以简单地写:
this.cboLengthUnit.DataSource = CreateBindingSource(unitsCollection, savedLengthUnit);
this.cboWidthUnit.DataSource = CreateBindingSource(unitsCollection, savedWidthUnit);
this.cboHeightUnit.DataSource = CreateBindingSource(unitsCollection, savedHeightUnit);
我是从内存中编写上述代码的,因此可能包含错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.