Last Updated :
17 Apr, 2023
In Windows forms, TextBox plays an important role. With the help of TextBox, the user can enter data in the application, it can be of a single line or of multiple lines. In TextBox, you are allowed to set the text associated with the TextBox by using the Text property of the TextBox. In Windows form, you can set this property in two different ways: 1. Design-Time: It is the simplest way to set the Text property of the TextBox as shown in the following steps:
2. Run-Time: It is a little bit tricky than the above method. In this method, you can set the Text property of the TextBox programmatically with the help of given syntax:
public override string Text { get; set; }
Here, the text is represented in the form of String. Following steps are used to set the Text property of the TextBox:
- Step 1 : Create a textbox using the TextBox() constructor provided by the TextBox class.
// Creating textbox TextBox Mytextbox = new TextBox();
- Step 2 : After creating TextBox set the Text property of the TextBox provided by the TextBox class.
// Set Text property Mytextbox.Text = "Enter City Name...";
- Step 3 : And last add this textbox control to form using Add() method.
// Add this textbox to form this.Controls.Add(Mytextbox);
- Example:
CSharp
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)
{
Label Mylablel =
new
Label();
Mylablel.Location =
new
Point(96, 54);
Mylablel.Text = "City";
Mylablel.AutoSize =
true
;
Mylablel.BackColor = Color.LightGray;
this
.Controls.Add(Mylablel);
TextBox Mytextbox =
new
TextBox();
Mytextbox.Location =
new
Point(187, 51);
Mytextbox.BackColor = Color.LightGray;
Mytextbox.ForeColor = Color.DarkOliveGreen;
Mytextbox.AutoSize =
true
;
Mytextbox.Name = "text_box1";
Mytextbox.Text = "Enter City Name...";
this
.Controls.Add(Mytextbox);
}
}
}
- Output:
Последнее обновление: 31.10.2015
Для ввода и редактирования текста предназначены текстовые поля — элемент TextBox. Так же как и у элемента Label текст элемента TextBox
можно установить или получить с помощью свойства Text.
По умолчанию при переносе элемента с панели инструментов создается однострочное текстовое поле. Для отображения больших объемов информации в
текстовом поле нужно использовать его свойства Multiline
и ScrollBars
.
При установке для свойства Multiline
значения true, все избыточные символы, которые выходят за границы поля, будут переноситься на
новую строку.
Кроме того, можно сделать прокрутку текстового поля, установив для его свойства ScrollBars
одно из значений:
-
None: без прокруток (по умолчанию)
-
Horizontal: создает горизонтальную прокрутку при длине строки, превышающей ширину текстового поля
-
Vertical: создает вертикальную прокрутку, если строки не помещаются в текстовом поле
-
Both: создает вертикальную и горизонтальную прокрутку
Автозаполнение текстового поля
Элемент TextBox обладает достаточными возможностями для создания автозаполняемого поля. Для этого нам надо привязать свойство
AutoCompleteCustomSource элемента TextBox к некоторой коллекции, из которой берутся данные для заполнения поля.
Итак, добавим на форму текстовое поле и пропишем в код события загрузки следующие строки:
public partial class Form1 : Form { public Form1() { InitializeComponent(); AutoCompleteStringCollection source = new AutoCompleteStringCollection() { "Кузнецов", "Иванов", "Петров", "Кустов" }; textBox1.AutoCompleteCustomSource = source; textBox1.AutoCompleteMode = AutoCompleteMode.SuggestAppend; textBox1.AutoCompleteSource = AutoCompleteSource.CustomSource; } }
Режим автодополнения, представленный свойством AutoCompleteMode, имеет несколько возможных значений:
-
None: отсутствие автодополнения
-
Suggest: предлагает варианты для ввода, но не дополняет
-
Append: дополняет введенное значение до строки из списка, но не предлагает варианты для выбора
-
SuggestAppend: одновременно и предлагает варианты для автодополнения, и дополняет введенное пользователем значение
Перенос по словам
Чтобы текст в элементе TextBox переносился по словам, надо установить свойство WordWrap равным true
. То есть если одно
слово не умещается на строке, то но переносится на следующую. Данное свойство будет работать только для многострочных текстовых полей.
Ввод пароля
Также данный элемент имеет свойства, которые позволяют сделать из него поле для ввода пароля. Так, для этого надо использовать PasswordChar
и UseSystemPasswordChar.
Свойство PasswordChar по умолчанию не имеет значение, если мы установим в качестве него какой-нибудь символ, то этот символ будут отображаться
при вводе любых символов в текстовое поле.
Свойство UseSystemPasswordChar имеет похожее действие. Если мы установим его значение в true
, то вместо введенных символов
в текстовом поле будет отображаться знак пароля, принятый в системе, например, точка.
Событие TextChanged
Из всех событий элемента TextBox следует отметить событие TextChanged
, которое срабатывает при изменении текста в элементе. Например, поместим
на форму кроме текстового поля метку и сделаем так, чтобы при изменении текста в текстовом поле также менялся текст на метке:
public partial class Form1 : Form { public Form1() { InitializeComponent(); textBox1.TextChanged += textBox1_TextChanged; } private void textBox1_TextChanged(object sender, EventArgs e) { label1.Text = textBox1.Text; } }
Суть в том, что есть кусочек кода, который выводит результат работы в консоль, а необходимо, чтобы он выводил на экран формы windows forms, несколько часов гугления не помогли
int a = 1;
int b = a;
int c;
for (int i = 0; i < 8; i++) {
c = a + b;
a = b;
b = c;
Console.WriteLine(c);
System.Threading.Thread.Sleep(1000);
}
-
Вопрос задан
-
14016 просмотров
Пригласить эксперта
int a = 1;
int b = a;
int c;
//Создаем форму
System.Windows.Forms.Form form = new System.Windows.Forms.Form();
//Задаем размер
form.Size = new System.Drawing.Size(640, 480);
//Создаем текстовое поле
System.Windows.Forms.RichTextBox richTextBox = new System.Windows.Forms.RichTextBox();
//Задаем размер поля на всю форму
richTextBox.Dock = System.Windows.Forms.DockStyle.Fill;
//Добавляем поле на форму
form.Controls.Add(richTextBox);
for (int i = 0; i < 8; i++) {
c = a + b;
a = b;
b = c;
//Записываем значение текста с новой строки
richTextBox.Text = richTextBox.Text + c + System.Environment.NewLine;
System.Threading.Thread.Sleep(1000);
}
Войдите, чтобы написать ответ
-
Показать ещё
Загружается…
Минуточку внимания
Although it is possible to use a simple MessageBox for printing messages, it is sometimes convenient to use a window that you have more control over. Below, I have the C# code for a simple console application named “MyConsoleApplication.” I created the project using the Console Application template, which creates the empty Main() function shown below. The code file is named “Program.cs” for simplicity, but it could be named anything.
We need to add a reference to the assembly System.Windows.Forms, in order to be able create Forms in the code. We also need to add the corresponding using directive using System.Windows.Forms; at the top of the code file. Finally, we need to add a reference to the assembly System.Drawing in order to set the size of the Form in the line: qMyForm.ClientSize = qMyTextbox.Size;.
Beyond that, the code that I have added is all inside the Main() function. First, I create a Form and add the text “An Important Message” to the title bar. Next, I create a TextBox and set its size to 400 by 300 pixels. Then I set it to accept multiple lines of text, enable the vertical scrollbar to accommodate text overruns, and set it to be read only so that the text cannot be modified.
The middle block of code consists of several calls to the member function AppendText(). Each call adds a line of text from the Bible, Proverbs 4:10-13. The character sequence \u000D\u000A is the unicode representation of the carriage return and linefeed characters. So, that moves the text to the beginning of the next line. On a related note, the TextBox has word wrap enabled by default.
The third block of code sets the size of the containing Form to have a client area that is the same size as the TextBox. Then the TextBox is added to the Form, and the Form is displayed via a call to ShowDialog().
The output of the program looks like this:
Program.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using FormStringOutput; using System.Windows.Forms; namespace MyConsoleApplication { class Program { static void Main(string[] args) { Form qMyForm = new Form(); // Sets the title bar text qMyForm.Text = "An Important Message"; TextBox qMyTextbox = new TextBox(); qMyTextbox.SetBounds(0, 0, 400, 300); qMyTextbox.Multiline = true; qMyTextbox.ScrollBars = ScrollBars.Vertical; qMyTextbox.ReadOnly = true; // Add messages via AppendText, using '\u000D\u000A' for new line characters qMyTextbox.AppendText("Hear, my child, and accept my words,\u000D\u000A"); qMyTextbox.AppendText(" that the years of your life may be many.\u000D\u000A"); qMyTextbox.AppendText("I have taught you the way of wisdom;\u000D\u000A"); qMyTextbox.AppendText(" I have led you in the paths of uprightness.\u000D\u000A"); qMyTextbox.AppendText("When you walk, your step will not be hampered;\u000D\u000A"); qMyTextbox.AppendText(" and if you run, you will not stumble.\u000D\u000A"); qMyTextbox.AppendText("Keep hold of instruction; do not let go;\u000D\u000A"); qMyTextbox.AppendText(" guard her, for she is your life.\u000D\u000A"); qMyTextbox.AppendText("\u000D\u000A Proverbs 4:10-13\u000D\u000A"); // Set the client area of the form equal to the size of the Text Box qMyForm.ClientSize = qMyTextbox.Size; // Add the Textbox to the form qMyForm.Controls.Add(qMyTextbox); // Display the form qMyForm.ShowDialog(); } } }
Tags: C Sharp, C#, form, GUI, message, message box, microsoft, programming, simple, text, textbox, windows
Michael Hall
By: Michael Hall
This entry was posted on Wednesday, August 6th, 2014 at 11:49 am and is filed under C Sharp. You can follow any responses to this entry through the RSS 2.0 feed.Both comments and pings are currently closed.