简体   繁体   English

C# 设计器覆盖 ComboBox 数据源

[英]C# Designer overwrites ComboBox DataSource

I am trying to set the DataSource of a ComboBox programmatically in InitializeComponent.我正在尝试在 InitializeComponent 中以编程方式设置 ComboBox 的数据源。

this.comboBox1.DataSource = (IEnumerable<> from a Linq command);

I save the file, everything works fine.我保存文件,一切正常。 However, as soon as I open the Designer, it overwrites my code.但是,只要我打开设计器,它就会覆盖我的代码。 What should I set in the Properties page to prevent Designer replaces my code with:我应该在“属性”页面中设置什么以防止 Designer 将我的代码替换为:

this.comboBox1.Items.AddRange( new object[] {
    "value1",
    "value2",
    ...
}

where the hardcoded list is the result of the Linq command.其中硬编码列表是 Linq 命令的结果。 Since the DataSource is set in an early line, the Designer throw exception complaining "DataSource cannot be changed after it's set".由于数据源设置在早期行中,设计器抛出异常,抱怨“数据源设置后无法更改”。

What should I specify on the Properties to prevent this from happening?我应该在属性上指定什么以防止这种情况发生? Thanks.谢谢。

You should not be editing InitializeComponent manually.您不应该手动编辑 InitializeComponent。 Instead, you should put that code in the constructor (or Load event) of your form/control.相反,您应该将该代码放入表单/控件的构造函数(或 Load 事件)中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM