TextBox和RichTextBox简单操作

.NET内置了两个基本控件来提取用户输入的文本:。这两个控件都派生于基类TextBoxBase,而TextBoxBase派生于Control。

TextBoxBase提供了在文本框中处理文本的基本功能,例如选择文本、剪切和从剪切板上粘贴,以及许多事件。

利用TextBox的Validating事件,将同类型输入验证进行代码归类,减少重复代码的编写。例如:姓名和地址两个输入框,验证规则为均不许为空,即可在初始化窗体时用如下代码进行相应验证事件的订阅

    this.txtName.Validating += new System.ComponentModel.CancelEventHandler(this.txtBoxEmpty_Validating);

    this.txtAddress.Validating += new System.ComponentModel.CancelEventHandler(this.txtBoxEmpty_Validating);

 

    private void txtBoxEmpty_Validating(object sender, System.ComponentModel.CancelEventArgs e)

    {

        TextBox tb;

        tb = (TextBox)sender;

        // If the text is empty we set the background color of the

        // TextBox to red to indicate a problem. We use the tag value

        // of the control to indicate if the control contains valid

        // information.

        if (tb.Text.Length == 0)

        {

            tb.BackColor = Color.Red;

            tb.Tag = false;

        }

        else

        {

            tb.BackColor = System.Drawing.SystemColors.Window;

            tb.Tag = true;

        }

    }

 

RichTextBox可以对其中的文本内容作一些格式化的显示,例如加粗、斜体、超级链接、居中等。

读取文本内容的小例子:

        /// <summary>

        /// 打开文件

        /// </summary>

        /// <param></param>

        /// <param></param>

        private void fbtnOpenFile_Click(object sender, System.EventArgs e)

        {

            openFileDialog1.ShowDialog();

            ftxtFilePath.Text = openFileDialog1.FileName;

        }

        /// <summary>

        /// 读取文件内容

        /// </summary>

        /// <param></param>

        /// <param></param>

        private void fbtnReadContent_Click(object sender, System.EventArgs e)

        {

            StreamReader sr = new StreamReader(ftxtFilePath.Text);

 

            string input;

            do

            {

                input = sr.ReadLine();

                if(input != "")

                {

                    this.frtbFileContent.Text += input + "\r\n";

                }

            }while(sr.Peek()!=-1);

 

            sr.Close();

        }

        /// <summary>

        /// 保存文件内容

        /// </summary>

        /// <param></param>

        /// <param></param>

        private void fbtnSaveContent_Click(object sender, System.EventArgs e)

        {

            StreamWriter sw = new StreamWriter(this.ftxtFilePath.Text);

            sw.Write(frtbFileContent.Text);

            sw.Flush();

            sw.Close();

        }

其中frtbFileContent控件为一个RichTextBox控件。

2006-4-7补上一个RichTextBox的小例子
    RichTextBox小例子下载

转载于:https://www.cnblogs.com/holygis/archive/2010/04/16/1713191.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值