468,268 Members | 1,701 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 468,268 developers. It's quick & easy.

user control, which way is better and How InitializeComponent() {} is generated? What to do if I need change code in InitializeComponent(){}?

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
Nov 16 '05 #1
0 965

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

5 posts views Thread by Nathan Sokalski | last post: by
reply views Thread by NPC403 | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.