WinForm真入门(17)——NumericUpDown控件详解
一、基本概念
NumericUpDown 是 Windows 窗体中用于数值输入的控件,由文本框和上下调节按钮组成。用户可通过以下方式调整数值:
- 点击调节按钮增减数值
- 键盘直接输入
- 使用方向键调整
适用于需要限制数值范围或精确控制的场景(如年龄、参数配置、数量选择等)。
二、核心属性
1、数值范围控制
- Minimum:允许的最小值(默认 0)
- Maximum:允许的最大值(默认 100)
- Value:当前显示的数值(默认 0)
- Increment:点击调节按钮时的增减步长(默认 1)
2、显示格式控制
- DecimalPlaces:设置小数位数(如 2 表示显示两位小数)
- ThousandsSeparator:启用千位分隔符(如 1,000)
3、交互控制
- ReadOnly:禁止用户直接输入(仅允许按钮调节)
- InterceptArrowKeys:启用方向键控制数值增减(默认 true)
三、常用方法
- UpButton():模拟点击“向上”按钮,增加数值
- DownButton():模拟点击“向下”按钮,减少数值
- UpdateEditText():强制更新文本框显示(如自定义格式化后调用)
四、使用案例
1、限制输入范围与步长
numericUpDown1.Minimum = 0;
numericUpDown1.Maximum = 1000;
numericUpDown1.Increment = 10; // 每次增减10:ml-citation{ref="1,6" data="citationList"}
2、格式化显示数值
numericUpDown1.DecimalPlaces = 2; // 显示两位小数
numericUpDown1.ThousandsSeparator = true; // 显示千位分隔符:ml-citation{ref="1,6" data="citationList"}
3、实时更新界面
private void numericUpDown1_ValueChanged(object sender, EventArgs e) {label1.Text = "当前值:" + numericUpDown1.Value.ToString("N2"); // 带两位小数格式化:ml-citation{ref="1,7" data="citationList"}
}
4、禁用非数字输入
numericUpDown1.KeyPress += (s, e) => {if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar)) {e.Handled = true; // 拦截非数字输入:ml-citation{ref="6,8" data="citationList"}}
};