views:

696

answers:

2

I have a numericupdown control on a C# Windows Form, and am interested in adding a leading zero to its value if it is < 10. (It is for the user to enter the minutes value of a time.)

I am not very familiar with overrides/inheriting yet in C# but it is looking as though I may have to do that.

It looks like this post on EggheadCafe has the answer I need. Is it as simple as making a new class and then creating a control of that new class?

public class TestNum : NumericUpDown
{
protected override void ValidateEditText()
{
if (base.UserEdit)
{
base.ValidateEditText();
}
}

protected override void UpdateEditText()
{
Text = Convert.ToInt32(base.Value).ToString("00");
}
}

When I try this, I am not sure how to create the new control that takes advantage of this class. I am using Visual Studio 2008. Still very new to windows forms. Thanks for any advice.

EDIT

I was able to make this work by editing the Designer-created code so that instead of the new control being of the original class, it was of the new one. So after adding the class above, I did the following (these changes are in two different locations, but I am only showing the lines that mattered):

Changed:

this.numTest = new System.Windows.Forms.NumericUpDown();
private System.Windows.Forms.NumericUpDown numTest;

To:

this.numTest = new SampleForm.TestNum();
private TestNum numTest;
+2  A: 

You need to use this newly created class in your form. It doesn't replace all NumericUpDown controls, it's a subclass.

Add the project which contains this class to the toolbox (Tools->Toolbox Items... - if memory serves) and you should be able to drag the control onto the form where you want to use it.

Niax
The UI control class must be contained in a separately compiled assembly (for it to appear in the toolbox and be usable for VS), so it must be contained in its own project.
Cecil Has a Name
Unfortunately it seems Cecil Has a Name is right, there doesn't seem to be a way to add this control to the toolbox.
JYelton
I was able to make this work by editing the Designer-created code, which I will edit into the question for clarity. Thanks for the help!
JYelton
+3  A: 

Why not just use a DateTimePicker control? Set it's ShowNumricUpDown property to true and set it's Format property to Custom and set the CustomFormat property to hh:mm:ss.

Perhaps this will be useful for you.

Chris

Chris Dunaway
This is a great idea, I didn't realize I could do that. +1 for the help, though I wound up discovering a way to implement the change to the numericupdown.
JYelton