Winform之TextBox(ConvertTo()数据类型转换)
1.拖出textBox
2.添加默认显示内容
3.修改控件名称
4.改多行输入显示模式
5.获取文本内容。
6.数据转换Convert.ToXXX
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Winform之TextBox
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
// 数据转换
// .Trim() 去除开始和尾部空格
int a = Convert.ToInt32(txt_A.Text.Trim());
int b = Convert.ToInt32(txt_B.Text.Trim());
int c = a + b;
txt_Sum.Text = c.ToString();
//Convert.ToDouble();
//MessageBox.Show();
}
}
}
TextBox(文本框)是 Windows Forms 应用程序中最常用的输入控件之一,它允许用户输入和编辑文本。
1. 基本使用
1.1 添加 TextBox 控件到窗体
- 打开 Visual Studio 并创建一个新的 Windows Forms 应用程序项目
- 从工具箱中拖拽 TextBox 控件到窗体设计器上
- 或者通过代码动态创建:
TextBox myTextBox = new TextBox();
myTextBox.Location = new Point(50, 50);
myTextBox.Size = new Size(200, 20);
this.Controls.Add(myTextBox);
1.2 常用属性
- Text:获取或设置文本框中的文本
- Name:控件的名称(用于代码中引用)
- Location:控件在窗体上的位置
- Size:控件的大小
- Multiline:是否允许多行文本输入
- ReadOnly:是否只读
- PasswordChar:用于密码输入的掩码字符(如
*
) - MaxLength:允许输入的最大字符数
- ScrollBars:当
Multiline=true
时,设置滚动条的显示方式 - WordWrap:是否自动换行(仅当
Multiline=true
时有效) - BorderStyle:边框样式(None, FixedSingle, Fixed3D)
- Font:文本字体
- ForeColor/ BackColor:文本和背景颜色
- AcceptsReturn:是否允许在多行文本框中按 Enter 键换行(而不是触发默认按钮)
- AcceptsTab:是否允许在多行文本框中按 Tab 键插入制表符
1.3 基本事件
- TextChanged:当文本框中的文本改变时触发
- KeyDown/KeyPress/KeyUp:键盘事件
- Enter/Leave:当控件获得或失去焦点时触发
- GotFocus/LostFocus:与 Enter/Leave 类似,但属于旧版事件
// 在设计器中双击文本框会自动生成TextChanged事件处理程序
private void textBox1_TextChanged(object sender, EventArgs e)
{
// 实时显示文本长度
toolStripStatusLabel1.Text = $"已输入 {textBox1.Text.Length} 个字符";
}
// 或者手动添加事件处理程序
myTextBox.TextChanged += MyTextBox_TextChanged;
private void MyTextBox_TextChanged(object sender, EventArgs e)
{
TextBox tb = sender as TextBox;
if (tb != null)
{
// 处理文本变化的代码
}
}
2. 高级用法
2.1 密码框实现
TextBox passwordBox = new TextBox();
passwordBox.Location = new Point(50, 80);
passwordBox.Size = new Size(200, 20);
passwordBox.PasswordChar = '*'; // 显示为星号
passwordBox.MaxLength = 16; // 限制密码长度
this.Controls.Add(passwordBox);
2.2 多行文本框
TextBox multiLineBox = new TextBox();
multiLineBox.Location = new Point(50, 110);
multiLineBox.Size = new Size(200, 100);
multiLineBox.Multiline = true;
multiLineBox.WordWrap = true;
multiLineBox.ScrollBars = ScrollBars.Vertical; // 垂直滚动条
multiLineBox.AcceptsReturn = true; // 允许按Enter换行
this.Controls.Add(multiLineBox);
2.3 输入验证
private void textBoxNumber_TextChanged(object sender, EventArgs e)
{
TextBox tb = sender as TextBox;
if (tb != null)
{
// 只允许输入数字
if (!System.Text.RegularExpressions.Regex.IsMatch(tb.Text, @"^[0-9]*$"))
{
// 如果不是数字,则移除最后一个字符
tb.Text = tb.Text.Remove(tb.Text.Length - 1);
tb.SelectionStart = tb.Text.Length; // 将光标移动到末尾
}
}
}
// 或者使用 KeyPress 事件进行更精确的控制
private void textBoxNumber_KeyPress(object sender, KeyPressEventArgs e)
{
if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar))
{
e.Handled = true; // 阻止非数字字符输入
}
}
2.4 水印效果(提示文本)
WinForms 本身不直接支持水印效果,但可以通过以下方式实现:
public class WatermarkTextBox : TextBox
{
private string watermarkText;
private Color watermarkColor = Color.Gray;
private Color originalForeColor;
public string WatermarkText
{
get { return watermarkText; }
set
{
watermarkText = value;
UpdateWatermark();
}
}
public WatermarkTextBox()
{
this.GotFocus += WatermarkTextBox_GotFocus;
this.LostFocus += WatermarkTextBox_LostFocus;
this.TextChanged += WatermarkTextBox_TextChanged;
}
private void WatermarkTextBox_GotFocus(object sender, EventArgs e)
{
UpdateWatermark();
}
private void WatermarkTextBox_LostFocus(object sender, EventArgs e)
{
UpdateWatermark();
}
private void WatermarkTextBox_TextChanged(object sender, EventArgs e)
{
UpdateWatermark();
}
private void UpdateWatermark()
{
if (string.IsNullOrEmpty(Text) && !string.IsNullOrEmpty(WatermarkText))
{
if (originalForeColor == Color.Empty)
{
originalForeColor = ForeColor;
}
ForeColor = watermarkColor;
Text = WatermarkText;
}
else if (ForeColor == watermarkColor && !string.IsNullOrEmpty(Text))
{
ForeColor = originalForeColor;
Text = Text; // 强制更新
}
}
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
// 如果需要更复杂的水印效果,可以在这里绘制
}
}
// 使用示例
WatermarkTextBox wtb = new WatermarkTextBox();
wtb.Location = new Point(50, 220);
wtb.Size = new Size(200, 20);
wtb.WatermarkText = "请输入用户名...";
this.Controls.Add(wtb);
2.5 拖放文本
// 启用拖放
textBox1.AllowDrop = true;
// 处理拖放事件
private void textBox1_DragEnter(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(DataFormats.Text))
{
e.Effect = DragDropEffects.Copy;
}
else
{
e.Effect = DragDropEffects.None;
}
}
private void textBox1_DragDrop(object sender, DragEventArgs e)
{
textBox1.Text = e.Data.GetData(DataFormats.Text).ToString();
}
3. 完整示例
下面是一个完整的示例,展示了一个带有多种功能的文本框:
using System;
using System.Drawing;
using System.Windows.Forms;
namespace TextBoxExample
{
public partial class MainForm : Form
{
private TextBox singleLineBox;
private TextBox passwordBox;
private TextBox multiLineBox;
private TextBox numberBox;
private WatermarkTextBox watermarkBox;
public MainForm()
{
InitializeComponent();
InitializeCustomControls();
}
private void InitializeCustomControls()
{
// 1. 单行文本框
singleLineBox = new TextBox();
singleLineBox.Location = new Point(20, 20);
singleLineBox.Size = new Size(200, 20);
singleLineBox.TextChanged += TextBox_TextChanged;
this.Controls.Add(singleLineBox);
// 2. 密码框
passwordBox = new TextBox();
passwordBox.Location = new Point(20, 50);
passwordBox.Size = new Size(200, 20);
passwordBox.PasswordChar = '*';
passwordBox.MaxLength = 16;
this.Controls.Add(passwordBox);
// 3. 多行文本框
multiLineBox = new TextBox();
multiLineBox.Location = new Point(20, 80);
multiLineBox.Size = new Size(200, 100);
multiLineBox.Multiline = true;
multiLineBox.WordWrap = true;
multiLineBox.ScrollBars = ScrollBars.Vertical;
multiLineBox.AcceptsReturn = true;
this.Controls.Add(multiLineBox);
// 4. 数字输入框
numberBox = new TextBox();
numberBox.Location = new Point(20, 190);
numberBox.Size = new Size(200, 20);
numberBox.KeyPress += NumberBox_KeyPress;
this.Controls.Add(numberBox);
// 5. 水印文本框
watermarkBox = new WatermarkTextBox();
watermarkBox.Location = new Point(20, 220);
watermarkBox.Size = new Size(200, 20);
watermarkBox.WatermarkText = "请输入搜索内容...";
this.Controls.Add(watermarkBox);
// 添加状态标签
Label statusLabel = new Label();
statusLabel.Location = new Point(20, 250);
statusLabel.AutoSize = true;
this.Controls.Add(statusLabel);
// 添加按钮显示文本
Button showTextButton = new Button();
showTextButton.Text = "显示文本";
showTextButton.Location = new Point(20, 280);
showTextButton.Click += (s, e) =>
{
string message = $"单行文本: {singleLineBox.Text}\n" +
$"密码: {new string('*', passwordBox.Text.Length)}\n" +
$"多行文本: {multiLineBox.Text}\n" +
$"数字: {numberBox.Text}\n" +
$"水印框文本: {watermarkBox.Text}";
MessageBox.Show(message, "文本内容");
};
this.Controls.Add(showTextButton);
}
private void TextBox_TextChanged(object sender, EventArgs e)
{
TextBox tb = sender as TextBox;
if (tb != null)
{
// 可以在这里添加对不同文本框的特定处理
}
}
private void NumberBox_KeyPress(object sender, KeyPressEventArgs e)
{
if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar))
{
e.Handled = true;
}
}
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new MainForm());
}
}
}
4. 最佳实践
- 命名规范:为文本框使用有意义的名称,如
txtUsername
、txtPassword
而不是textBox1
- 数据验证:始终验证用户输入,特别是在保存到数据库或进行计算前
- 安全性:对于密码等敏感信息,使用
PasswordChar
属性并考虑加密存储 - 国际化:如果应用需要支持多语言,考虑使用资源文件存储文本框的提示信息
- 性能:对于大量文本处理,考虑使用
BeginUpdate()
和EndUpdate()
方法(虽然 TextBox 没有这些方法,但在类似场景中适用) - 可访问性:为文本框设置适当的
AccessibleName
和AccessibleDescription
属性
5. 常见问题解决
问题1:文本框无法输入中文
- 检查键盘布局设置
- 确保没有事件处理程序阻止了输入
问题2:多行文本框无法换行
- 确认
Multiline
属性设置为 true - 确认
WordWrap
属性设置为 true(如果需要自动换行) - 如果
AcceptsReturn
为 false,按 Enter 不会换行而是触发默认按钮
问题3:文本框显示乱码
- 检查字体设置是否支持目标语言
- 确保文本编码正确(通常不需要特别处理,但处理文件输入时要注意)
问题4:如何清空文本框
textBox1.Clear(); // 或者 textBox1.Text = "";
问题5:如何获取文本框中的所有文本
string allText = textBox1.Text; // 对于多行文本框,这会获取所有行