本文将从多个方面对c#textbox进行详细的阐述,并给出代码示例。
一、textbox基本操作
textbox是一个文本框控件,常用于输入、输出和编辑文本。以下是一些基本操作:
- 获取textbox文本内容:
- 设置textbox文本内容:
- 清空textbox文本内容:
string text = textBox1.Text;
textBox1.Text = "Hello, World!";
textBox1.Clear();
二、textbox文本格式化
textbox支持多种格式化设置,可以将文本内容格式化为货币、日期、数值等。以下是一些例子:
- 设置文本格式为货币:
- 设置文本格式为日期:
- 设置文本格式为数值:
textBox1.Text = string.Format("{0:C}", 1234.56);
textBox1.Text = string.Format("{0:d}", DateTime.Now);
textBox1.Text = string.Format("{0:N}", 1234.56);
三、textbox输入验证
textbox可以对用户输入的文本内容进行验证,如限制输入的字符类型、长度、范围等。以下是一些常用的验证方法:
- 限制用户只能输入数字:
- 限制用户只能输入指定长度的文本:
- 验证文本内容是否符合指定的范围:
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (!char.IsDigit(e.KeyChar))
{
e.Handled = true;
}
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
if (textBox1.Text.Length > 10)
{
textBox1.Text = textBox1.Text.Substring(0, 10);
textBox1.Select(textBox1.Text.Length, 0);
}
}
private void button1_Click(object sender, EventArgs e)
{
int value = 0;
if (!int.TryParse(textBox1.Text, out value))
{
MessageBox.Show("请输入有效的数字");
}
else if (value 100)
{
MessageBox.Show("请输入范围在0~100之间的数字");
}
else
{
textBox1.Text = value.ToString();
}
}
四、textbox高级用法
textbox还有一些高级用法,如自动补全、自动换行、事件绑定等。以下是一些例子:
- textbox自动补全:
- textbox自动换行:
- textbox事件绑定:
private void textBox1_TextChanged(object sender, EventArgs e)
{
string keyword = textBox1.Text;
string[] items = { "Apple", "Banana", "Orange", "Pear" };
var matchedItems = items.Where(x => x.ToLower().Contains(keyword.ToLower())).ToArray();
listBox1.Items.Clear();
if (matchedItems.Length > 0)
{
listBox1.Items.AddRange(matchedItems);
listBox1.Visible = true;
}
else
{
listBox1.Visible = false;
}
}
private void listBox1_Click(object sender, EventArgs e)
{
textBox1.Text = listBox1.SelectedItem.ToString();
listBox1.Visible = false;
}
textBox1.Multiline = true;
textBox1.WordWrap = true;
textBox1.KeyPress += new KeyPressEventHandler(textBox1_KeyPress);
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (!char.IsDigit(e.KeyChar))
{
e.Handled = true;
}
}