Reputation: 2145
I've created a very simple NumericUpDownPlus which overrides the UpdateEditText method in the following way: (As per this SO question: Having text inside NumericUpDown control, after the number)
protected override void UpdateEditText()
{
if (string.IsNullOrWhiteSpace(Units))
{
base.UpdateEditText();
}
else
{
this.Text = this.Value + " " + Units;
}
}
However, this causes me problems when editing the control manually. In this case, I'm appending " px" as my Units, and the following situations can arise:
Of course, I'm only interested in the number, and don't care what unit is being used, it's just a convenience for the user. How can I get this NumericUpDown to cooperate? I was thinking of just clearing the box when control gets focus, but I feel like this might not be the best solution.
Upvotes: 2
Views: 1413
Reputation: 115
I have the same problem when i want to add currency format, i resolve this by override text Property:
[Bindable(false)]
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
[EditorBrowsable(EditorBrowsableState.Never)]
public override string Text
{
get
{
string formattedValue = ParseEditText(base.Text);
return formattedValue;
}
set
{
base.Text = value;
}
}
protected override void UpdateEditText()
{
string formatSpecifier = "N";
switch (DisplayFormatSpecifier)
{
case DisplayFormatSpecifier.Euro:
formatSpecifier = "C";
break;
case DisplayFormatSpecifier.Percent:
formatSpecifier = "P";
break;
case DisplayFormatSpecifier.Number:
formatSpecifier = "N";
break;
default:
formatSpecifier = "N";
break;
}
formatSpecifier += DecimalPlaces.ToString();
this.Text = this.Value.ToString(formatSpecifier.ToString(), formatProvider);
}
/// <summary>
/// Remove the last character if is not a digit
/// </summary>
private string ParseEditText(string text)
{
string textReplace = text;
if (!string.IsNullOrWhiteSpace(text))
{
char c = text[text.Length - 1];
if (!char.IsDigit(c))
{
textReplace = textReplace.Replace(c.ToString(), string.Empty);
}
}
return textReplace;
}
Upvotes: 0
Reputation: 63317
protected override void UpdateEditText() {
if (string.IsNullOrWhiteSpace(Units)) {
base.UpdateEditText();
} else {
try {
Value = decimal.Parse(Text.Replace(Units, "").Trim());
} catch {
base.UpdateEditText();
}
this.Text = this.Value + " " + Units;
}
}
Upvotes: 1
Reputation: 700
protected override void UpdateEditText()
{
base.ParseEditText();
if (!string.IsNullOrEmpty(this.Text))
{
decimal value;
decimal.TryParse(this.Text.Replace(Units,"").Trim(),out value);
this.Value = value;
}
this.Text = this.Value + " " + Units;
}
Try this out.
Upvotes: 0