派生ComboBox的诡异问题

drhouse 2008-11-27 01:18:29
想要一个显示若干固定年份的ComboBox,所以派生了ComboBox,在构造函数里面添加年份。

然后在窗体设计器中,把YearComboBox拖到form上,结果发现,设计器生成的代码中
竟然又把这些年份添加了一遍。似乎是设计器自动解析了我的构造函数生成了相应代码。结果现在的下拉框里面年份列表被添加了两次。

请问这是什么原因呢?

C#,VS2008

代码如下:
============YearCombobox.cs===============================

class YearComboBox: ComboBox
{
public YearComboBox()
{
this.DropDownStyle = ComboBoxStyle.DropDownList;
for (int i = 1998; i < 2008; i++)
{
this.Items.Add(i);
}

this.SelectedItem = 2000;

}

int SelectYear
{
get
{
return (int)this.SelectedItem;
}
set
{
this.SelectedItem = value;
}
}

}
=========================================


==============Form1.Designer.cs=============================
private void InitializeComponent()
{
...
...

this.yearComboBox21.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.yearComboBox21.FormattingEnabled = true;
this.yearComboBox21.Items.AddRange(new object[] {
1998,
1999,
2000,
2001,
2002,
2003,
2004,
2005,
2006,
2007});
...
...
}
...全文
72 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
zzandww 2008-11-27
  • 打赏
  • 举报
回复
我也经常碰到这个问题。理论上好像添加的时候

public YearComboBox()
{
if(!DesignMode)
this.DropDownStyle = ComboBoxStyle.DropDownList;
for (int i = 1998; i < 2008; i++)
{
this.Items.Add(i);
}

this.SelectedItem = 2000;
}
}
这样子试试。
drhouse 2008-11-27
  • 打赏
  • 举报
回复
忘了给分了,请问怎么才能编辑自己发的帖子呢,为什么说我没有权限

111,130

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Creator Browser
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧