Question

WinForms NumericUpDown allows us to select a range of the text inside it using the Select(Int32, Int32) method. Is there any way to set/retrieve the starting point of text selected, the number of characters selected and the selected part of text like we can do that for other textbox-like controls using the SelectionStart, SelectionLength and SelectedText properties?

Was it helpful?

Solution

The NumericUpDown control has an internal TextBox accessible from the controls collection. It's the second control in the collection following the UpDownButtons control. Since WinForms isn't under development any longer, it's practically safe to say the underlying architecture of the NumericUpDown control isn't going to change.

By inheriting from the NumericUpDown control, you can easily expose those TextBox properties:

public class NumBox : NumericUpDown {
  private TextBox textBox;

  public NumBox() {
    textBox = this.Controls[1] as TextBox;
  }

  public int SelectionStart {
    get { return textBox.SelectionStart; }
    set { textBox.SelectionStart = value; }
  }

  public int SelectionLength {
    get { return textBox.SelectionLength; }
    set { textBox.SelectionLength = value; }
  }

  public string SelectedText {
    get { return textBox.SelectedText; }
    set { textBox.SelectedText = value; }
  }
}

OTHER TIPS

Similar to LarsTech's answer, you can quickly cast the NumericUpDown.Controls[1] as a TextBox to access these properties without creating a new class.

((TextBox)numericUpDown1.Controls[1]).SelectionLength; // int
((TextBox)numericUpDown1.Controls[1]).SelectionStart; // int
((TextBox)numericUpDown1.Controls[1]).SelectedText; // string

This is not possible with the vanilla NumericUpDown control.

In this article, the author explains how he subclassed the NumericUpDown control to expose the underlying TextBox object, and thus exposing the "missing" properties:

http://www.codeproject.com/Articles/30899/Extended-NumericUpDown-Control

He uses reflection to get a reference to the underlying TextBox object:

private static TextBox GetPrivateField(NumericUpDownEx ctrl)
{
    // find internal TextBox
    System.Reflection.FieldInfo textFieldInfo = typeof(NumericUpDown).GetField("upDownEdit", System.Reflection.BindingFlags.FlattenHierarchy | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
    // take some caution... they could change field name
    // in the future!
    if (textFieldInfo == null) {
        return null;
    } else {
        return textFieldInfo.GetValue(ctrl) as TextBox;
    }
}

Cheers

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top