Having trouble with custom combobox control

G

Guest

Hello,

I am beginning to write a custom combobox control. Right now it doesn't do
anything special. I created a class that extends ComboBox:

public class TimeSelector : System.Windows.Forms.ComboBox

and in its constructor I call Populate:

public TimeSelector()
{
try
{
if(!DesignMode)
{
Populate();
}
}
catch(Exception ex_)
{
MessageBox.Show(ex_.Message);
}
}

where Populate is as follows:

private void Populate()
{
Items.Clear();
string[] times = new String[48];
DateTime dt = new DateTime(1,1,1,23,30,0,0);
for(int i = 0; i < 48; i++)
{
dt = dt.Add(new TimeSpan(0,30,0));
times = dt.ToString("h:mm tt");
}
DataSource = times;
}

Now, when I start an empty form that contains this control, the combobox
correctly contains all of the items that I populated it with. However,
whenever I do anything to the control while I am looking at the form that
contains it in design mode, it gets messed up.

Specifically, when I go back to look at InitializeComponent in the form's
code, it seems to have added all of the times to the combobox thru a
DataSource and then it manually adds each time to the combobox's Items
collection right after that:

this.ts.DataSource = new string[] {
"12:00 AM",
"12:30 AM",
"1:00 AM",...

this.ts.Items.AddRange(new object[] {
"12:00 AM",
"12:30 AM",
"1:00 AM",...

This causes an error because you can't modify the combox's Items while it is
data bound. And this happens no matter what I do while in design mode (if I
move the control, set Enabled to false, whatever).

Can someone tell me what I am doing wrong?

Thanks,
-Flack
 
B

Bruce Wood

I can see one thing immediately wrong.

You are testing to see whether you are in DesignMode, and populating
the combo box, in its constructor. The DesignMode property only words
after you have a window context for your control, and the constructor
is too early for that. You should be doing all of this work in the
control's OnLoad method, not in the constructor:

protected override void OnLoad(object sender, System.EventArgs e)
{
base.OnLoad(sender, e);

try
{
if(!DesignMode)
{
Populate();
}
}
catch(Exception ex_)
{
MessageBox.Show(ex_.Message);
}
}
 
G

Guest

Thanks for the reply.

I tried to do what you suggested but the combo box has no OnLoad method for
me to override.
 
B

Bruce Wood

Silly me. I was thinking of Form when I wrote that.

The closest thing I can find to try is OnCreateControl(). According to
the doc, this is called when the control handle is first created, so
that should be the right place to test DesignMode and have it be
meaningful.

I've never tried overriding OnCreateControl, but it's worth a shot.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top