📌  相关文章
📜  如何在C#中使用TextBox的AcceptsReturn属性?

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

在TextBox中,您可以设置一个值,该值显示在多行TextBox控件中按ENTER键是在TextBox控件中创建新的一行文本还是通过使用AcceptsReturn属性激活表单的默认按钮。
如果此属性的值设置为true,则ENTER键将在多行TextBox控件中创建一行新文本,并且如果此属性的值设置为false,则ENTER键将激活表单的默认按钮。此属性的默认值为false。在Windows窗体中,可以用两种不同的方式设置此属性:

1.设计时:这是设置TextBox的AcceptsReturn属性的最简单方法,如以下步骤所示:

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

    输出:

运行时:比以前的方法有些棘手。在此方法中,可以借助给定的语法以编程方式设置TextBox的AcceptsReturn属性:

public bool AcceptsReturn { get; set; }

在此,此属性为System.Boolean类型的值。以下步骤用于设置TextBox的AcceptsReturn属性:

  • 步骤1:使用TextBox类提供的TextBox()构造函数创建一个文本框。
    // Creating textbox
    TextBox Mytextbox = new TextBox();
    
  • 步骤2:创建TextBox之后,设置TextBox类提供的TextBox的AcceptsReturn属性。
    // Set AcceptsReturn property
    Mytextbox.AcceptsReturn = false;
    
  • 第3步:最后使用Add()方法将此文本框控件添加到中。
    // Add this textbox to form
    this.Controls.Add(Mytextbox);
    

    例子:

    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 my {
      
    public partial class Form1 : Form {
      
        public Form1()
        {
            InitializeComponent();
        }
      
        private void Form1_Load(object sender, EventArgs e)
        {
            // Creating and setting the properties of Lable1
            Label Mylablel = new Label();
            Mylablel.Location = new Point(96, 54);
            Mylablel.Text = "Name";
            Mylablel.AutoSize = true;
            Mylablel.BackColor = Color.LightGray;
      
            // Add this label to form
            this.Controls.Add(Mylablel);
      
            // Creating and setting the properties of TextBox1
            TextBox Mytextbox = new TextBox();
            Mytextbox.Location = new Point(187, 51);
            Mytextbox.BackColor = Color.LightGray;
            Mytextbox.ForeColor = Color.DarkOliveGreen;
            Mytextbox.AutoSize = true;
            Mytextbox.AcceptsReturn = false;
      
            // Add this textbox to form
            this.Controls.Add(Mytextbox);
        }
    }
    }
    

    输出: