Хитрость заключается в том, чтобы вставить текстовое поле в числовой элемент управления обновлением и обработать его событие Validating.
Вот как это сделать:
Создайте фиктивную форму и добавьте числовой элемент управления обновлением и некоторые другие элементы управления, а когда числовой элемент управления отключением теряет фокус, текст формы будет иметь значение, введенное пользователем.
Вот код того, что я сделал:
public partial class Form1 : Form
{
TextBox txt;
public Form1()
{
InitializeComponent();
txt = (TextBox)numericUpDown1.Controls[1];//notice the textbox is the 2nd control in the numericupdown control
txt.Validating += new CancelEventHandler(txt_Validating);
}
void txt_Validating(object sender, CancelEventArgs e)
{
this.Text = txt.Text;
}
}
EDIT:
@ Carlos_Liu: Хорошо, теперь я вижу проблему, вы можете добиться этого с помощью события TextChanged, просто сохраните значение в фиктивной переменной и повторно используйте его при txt_Validating, но будьте осторожны, не обновляйте это переменная, если текстовое поле не сфокусировано .
Вот новый пример кода:
public partial class Form1 : Form
{
TextBox txt;
string val;
public Form1()
{
InitializeComponent();
txt = (TextBox)numericUpDown1.Controls[1];//notice the textbox is the 2nd control in the numericupdown control
txt.TextChanged += new EventHandler(txt_TextChanged);
txt.Validating += new CancelEventHandler(txt_Validating);
}
void txt_TextChanged(object sender, EventArgs e)
{
if (txt.Focused) //don't save the value unless the textbox is focused, this is the new trick
val = txt.Text;
}
void txt_Validating(object sender, CancelEventArgs e)
{
MessageBox.Show("Val: " + val);
}
}
EDIT # 2
@ Carlos_Liu: Если вам нужно сохранить введенное значение, все же для этого есть хитрость: @ Событие проверки текстового поля, проверьте значение, если оно не в пределах диапазона, отмените потерю фокуса!
Вот новая версия кода:
public partial class Form1 : Form
{
TextBox txt;
string val;
public Form1()
{
InitializeComponent();
txt = (TextBox)numericUpDown1.Controls[1];
txt.TextChanged += new EventHandler(txt_TextChanged);
txt.Validating += new CancelEventHandler(txt_Validating);
}
void txt_TextChanged(object sender, EventArgs e)
{
if (txt.Focused)
val = txt.Text;
}
void txt_Validating(object sender, CancelEventArgs e)
{
int enteredVal = 0;
int.TryParse(val, out enteredVal);
if (enteredVal > numericUpDown1.Maximum || enteredVal < numericUpDown1.Minimum)
{
txt.Text = val;
e.Cancel = true;
}
}
}