c#textbox使用用法介绍(C学习笔记TextBox使用)

本文将从多个方面对c#textbox进行详细的阐述,并给出代码示例。

一、textbox基本操作

textbox是一个文本框控件,常用于输入、输出和编辑文本。以下是一些基本操作:

  1. 获取textbox文本内容:
  2. string text = textBox1.Text;
  3. 设置textbox文本内容:
  4. textBox1.Text = "Hello, World!";
  5. 清空textbox文本内容:
  6. textBox1.Clear();

二、textbox文本格式化

textbox支持多种格式化设置,可以将文本内容格式化为货币、日期、数值等。以下是一些例子:

  1. 设置文本格式为货币:
  2. textBox1.Text = string.Format("{0:C}", 1234.56);
  3. 设置文本格式为日期:
  4. textBox1.Text = string.Format("{0:d}", DateTime.Now);
  5. 设置文本格式为数值:
  6. textBox1.Text = string.Format("{0:N}", 1234.56);

三、textbox输入验证

textbox可以对用户输入的文本内容进行验证,如限制输入的字符类型、长度、范围等。以下是一些常用的验证方法:

  1. 限制用户只能输入数字:
  2. private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
    {
        if (!char.IsDigit(e.KeyChar))
        {
            e.Handled = true;
        }
    }
  3. 限制用户只能输入指定长度的文本:
  4. 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);
        }
    }
  5. 验证文本内容是否符合指定的范围:
  6. 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还有一些高级用法,如自动补全、自动换行、事件绑定等。以下是一些例子:

  1. textbox自动补全:
  2. 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;
    }
  3. textbox自动换行:
  4. textBox1.Multiline = true;
    textBox1.WordWrap = true;
  5. textbox事件绑定:
  6. textBox1.KeyPress += new KeyPressEventHandler(textBox1_KeyPress);
    private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
    {
        if (!char.IsDigit(e.KeyChar))
        {
            e.Handled = true;
        }
    }

Published by

风君子

独自遨游何稽首 揭天掀地慰生平