H_J_H

------专用杂物房
posts - 26, comments - 1, trackbacks - 0, articles - 119

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

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

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

    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 name="sender"></param>

        /// <param name="e"></param>

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

        {

            openFileDialog1.ShowDialog();

            ftxtFilePath.Text = openFileDialog1.FileName;

        }

        /// <summary>

        /// 读取文件内容

        /// </summary>

        /// <param name="sender"></param>

        /// <param name="e"></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 name="sender"></param>

        /// <param name="e"></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-02-17 11:13
只有注册用户登录后才能发表评论。