📜  如何在C#中的RichTextBox中添加文本?

📅  最后修改于: 2021-05-29 23:00:57             🧑  作者: Mango

在C#中,RichTextBox控件是一个文本框,可为您提供富文本编辑控件,而高级格式设置功能还包括加载富文本格式(RTF)文件。换句话说,RichTextBox控件允许您显示或编辑流内容,包括段落,图像,表格等。在RichTextBox中,您可以在使用Text Property在屏幕上显示的RichTextBox控件中添加文本。您可以通过两种不同的方式设置此属性:

1.设计时:这是在RichTextBox中添加文本的最简单方法,如以下步骤所示:

  • 第1步:创建一个Windows窗体,如下图所示:
    Visual Studio->文件->新建->项目-> WindowsFormApp
  • 步骤2:从工具箱中拖动RichTextBox控件,并将其放在Windows窗体上。您可以根据需要将RichTextBox控件放置在Windows窗体上的任何位置。
  • 步骤3:拖放之后,您将转到RichTextBox控件的属性以在RichTextBox控件中添加文本。

    输出:

2.运行时:比上述方法有些棘手。在此方法中,可以在给定语法的帮助下以编程方式在RichTextBox控件中添加文本:

public override string Text { get; set; }

在这里,此属性的值是System.String类型。以下步骤显示如何动态设置RichTextBox的Text属性:

  • 步骤1:使用RichTextBox类提供的RichTextBox()构造函数创建RichTextBox。
    // Creating RichTextBox using RichTextBox class constructor
    RichTextBox rbox = new RichTextBox();
    
  • 步骤2:创建RichTextBox之后,设置RichTextBox类提供的RichTextBox的Text属性。
    // Adding text in the control box
    rbox.Text = "!..Welcome to GeeksforGeeks..!";
    
  • 步骤3:最后使用Add()方法将此RichTextBox控件添加到表单中。
    // Add this RichTextBox to the form
    this.Controls.Add(rbox);
    

    例子:

    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 WindowsFormsApp30 {
      
    public partial class Form1 : Form {
      
        public Form1()
        {
            InitializeComponent();
        }
      
        private void Form1_Load(object sender, EventArgs e)
        {
            // Creating and setting the 
            // properties of the label
            Label lb = new Label();
            lb.Location = new Point(251, 70);
            lb.Text = "Enter Text";
      
            // Adding this label in the form
            this.Controls.Add(lb);
      
            // Creating and setting the
            // properties of RichTextBox
            RichTextBox rbox = new RichTextBox();
            rbox.Location = new Point(236, 97);
            rbox.ForeColor = Color.Red;
            rbox.Text = "!..Welcome to GeeksforGeeks..!";
      
            // Adding this RichTextBox in the form
            this.Controls.Add(rbox);
        }
    }
    }
    

    输出: