I think there are two way to define user control.
For example, I want to define a ComoBox with contains only AM, PM items.
a.. One way I define a class extends System.Windows.Forms.UserControl,
and put a ComboBox on it.
b.. Another is Ithat I define a class (TimeSegmentComboBox ) extends
ComboBox.
Either way, I have code to populate AM, PM to Combox.
In the second case:
public class TimeSegmentComboBox : ComboBox
{
public TimeSegmentComboBox() //constructor
{
InitializeComponent();
if(!this.populated)
{
this.AddItemsCore(new object[] {TimeSegment.AM , TimeSegment.PM});
this.SelectedIndex = 1;
this.populated = true; //this flag does not help
}
}
}
I prefer this second way, but it has a problem. When I put this user control
on a form in Visual Studio 2003, it generated code including
code add AM PM to Combox again.
private void InitializeComponent()
{
.......
//
// timeSegmentComboBox1
//
this.timeSegmentComboBox1.Items.AddRange(new object[]
{TimeSegment.AM,TimeSegment.PM}); //need manually remove this line later
this.timeSegmentComboBox1.Location = new System.Drawing.Point(136, 184);
this.timeSegmentComboBox1.Name = "timeSegmentComboBox1";
this.timeSegmentComboBox1.Size = new System.Drawing.Size(80, 21);
.......
}
This way, the code populate Combox with AM, PM will be shown and executed
twice. I can only manually delete the code generated by Visual Studio in
Form1.cs. But the code in InitializeComponent() should not be manually
edited.
So my first question, is what is the mechanism for Visual Studio to
auto-generate InitializeComponent() for (user) controls?
The second question is, when there is a need to modify
InitializeComponent(), what is the better solution? If I manually edit
anything, I lost it when I go to design view.
Thanks a lot!
Ryan