Покажем, как выполнить перенос строки в TextBox с атрибутом Multiline (когда текстовое поле занимает несколько строк). Сделаем это на примере программы в Windows Forms и языка C#.
Создание интерфейса программы для демонстрации переноса строки в TextBox
Создадим проект Windows Forms. На окне формы расположим два элемента управления: кнопку (Button) и текстовое поле (TextBox). В кнопке параметру Text зададим значение «Прочитать файл», поскольку текст в TextBox будем считывать из файла.
Далее займёмся настройкой TextBox. Нажмите правой кнопкой на данном элементе управления и перейдите к Свойствам.
Значение атрибута Multiline установим, как True. Это позволит выводить в TextBox текст в несколько строк, а не в одну.
Далее активируем полосы прокрутки у TextBox. Это позволит удобнее просматривать и работать с многострочным текстом. Для активации параметр ScrollBars переведём в положение Both — полосы будут по обоим измерениям: по горизонтали и по вертикали.
Растянем TextBox по горизонтали до низа формы и получим нечто подобное:
Интерфейс программы готов.
Создание кода программы для показа возможности перехода на новую строку в TextBox
В Visual Studio два раза щёлкнем на кнопку (Button). Откроется редактор кода обработки нажатия на кнопку. Добавим следующие строки:
private void button1_Click(object sender, EventArgs e) { textBox1.Text = «»; StreamReader sr = new StreamReader(«input.txt», System.Text.Encoding.Default); while (!sr.EndOfStream) textBox1.Text += sr.ReadLine() + Environment.NewLine; sr.Close(); } |
Разберём код. При нажатии на кнопку «Прочитать файл» сначала будет очищен TextBox (строка 3). Затем создастся экземпляр класса StreamReader, который необходим для чтения файла (строка 5). В конструктор экземпляра будут переданы следующие аргументы: имя входного файла (input.txt) и его кодировка (по умолчанию).
Далее в цикле while происходит построчное чтение файла до конца (строки 7-8). При этом к каждой считанной строке добавляется элемент Environment.NewLine. Он производит переход курсора на новую строку.
Считывающий поток закрывается с помощью метода Close (строка 10).
Конец файла определяется с помощью значения EndOfStream. Когда достигнут конец оно равно true; в остальных случаях — false.
Значение Environment.NewLine является универсальным для любого окружения, поэтому его предпочтительнее использовать, чем управляющие символы. Но если очень хочется, то переход на новую строку можно выполнить и так:
textBox1.Text += sr.ReadLine() + ‘r’ + ‘n’; |
Обратите внимание, что используется два управляющий символа: возврат каретки r и переход на новую строку n. Если не использовать возврат каретки, то ничего не сработает и весь текст будет записан в одну строку.
Написание кода для программы, демонстрирующей перенос строки в TextBox с Multiline, завершено. Теперь подготовим входной файл с текстом.
Его необходимо поместить в каталог ../bin/Debug из папки с проектом.
Запустим программу и посмотрим переход на новую строку в TextBox в действии. Нажмём на кнопку «Прочитать файл».
Скачать исходник программы для Visual Studio из данного урока программирования, можно, нажав на кнопку ниже:
Скачать исходник
В статье был разобран перенос строки в TextBox с Multiline в программе Windows Forms на языке программирования C#. Спасибо за прочтение!
I’m doing a chat client, and currently I have a button that will display data to a multi-line textbox when clicked. Is this the only way to add data to the multi-line textbox? I feel this is extremely inefficient, because if the conversation gets really long the string will get really long as well.
private void button1_Click(object sender, EventArgs e)
{
string sent = chatBox.Text;
displayBox.Text += sent + "rn";
}
Tilak
29.7k19 gold badges81 silver badges130 bronze badges
asked Nov 10, 2012 at 2:07
Brandon LingBrandon Ling
3,7616 gold badges31 silver badges49 bronze badges
3
If you use WinForms:
Use the AppendText(myTxt)
method on the TextBox
instead (.net 3.5+):
private void button1_Click(object sender, EventArgs e)
{
string sent = chatBox.Text;
displayBox.AppendText(sent);
displayBox.AppendText(Environment.NewLine);
}
Text in itself has typically a low memory footprint (you can say a lot within f.ex. 10kb which is «nothing»). The TextBox does not render all text that is in the buffer, only the visible part so you don’t need to worry too much about lag. The slower operations are inserting text. Appending text is relatively fast.
If you need a more complex handling of the content you can use StringBuilder
combined with the textbox. This will give you a very efficient way of handling text.
answered Nov 10, 2012 at 7:48
1
Following are the ways
-
From the code (the way you have mentioned) ->
displayBox.Text += sent + "rn";
or
displayBox.Text += sent + Environment.NewLine;
-
From the UI
a) WPFSet TextWrapping="Wrap" and AcceptsReturn="True"
Press Enter key to the textbox and new line will be created
b) Winform text box
Set TextBox.MultiLine and TextBox.AcceptsReturn to true
answered Nov 10, 2012 at 3:56
TilakTilak
29.7k19 gold badges81 silver badges130 bronze badges
1
I find this method saves a lot of typing, and prevents a lot of typos.
string nl = "rn";
txtOutput.Text = "First line" + nl + "Second line" + nl + "Third line";
StayOnTarget
11k10 gold badges49 silver badges75 bronze badges
answered Feb 23, 2018 at 15:05
0
I use this function to keep newest at top:
WriteLog("hello1");
WriteLog("hello2");
WriteLog("hello3");
public void WriteLog(string text)
{
var last = txtLog.Text;
txtLog.Text = DateTime.Now.ToString("G") + ": " + text;
txtLog.AppendText(Environment.NewLine);
txtLog.AppendText(last);
}
Will output this:
answered May 15, 2022 at 5:10
kuhikuhi
4633 silver badges18 bronze badges
Because you haven’t specified what front end (GUI technology) you’re using it would be hard to make a specific recommendation. In WPF you could create a listbox and for each new line of chat add a new listboxitem to the end of the collection. This link provides some suggestions as to how you may achieve the same result in a winforms environment.
answered Nov 10, 2012 at 3:35
alanalan
6,5259 gold badges39 silver badges68 bronze badges
5
C# — serialData is ReceivedEventHandler
in TextBox
.
SerialPort sData = sender as SerialPort;
string recvData = sData.ReadLine();
serialData.Invoke(new Action(() => serialData.Text = String.Concat(recvData)));
Now Visual Studio drops my lines. TextBox, of course, had all the correct options on.
Serial:
Serial.print(rnd);
Serial.( 'n' ); //carriage return
Acapulco
3,2938 gold badges37 silver badges50 bronze badges
answered Sep 25, 2018 at 16:31
ArturKaktus 3 / 3 / 3 Регистрация: 21.10.2014 Сообщений: 113 |
||||
1 |
||||
11.08.2015, 09:48. Показов 18294. Ответов 5 Метки нет (Все метки)
всем доброго времени суток, проблема вот в чем:
не могу переходить на новую строку…
__________________
0 |
4 / 4 / 3 Регистрация: 06.05.2015 Сообщений: 93 |
|
11.08.2015, 09:55 |
2 |
ArturKaktus, вам надо каждый раз с новой строки чтобы писалось? да?
0 |
Jim Beam 83 / 83 / 55 Регистрация: 30.01.2015 Сообщений: 137 |
||||
11.08.2015, 10:03 |
3 |
|||
Решение
3 |
3 / 3 / 3 Регистрация: 21.10.2014 Сообщений: 113 |
|
11.08.2015, 10:09 [ТС] |
4 |
ArturKaktus, вам надо каждый раз с новой строки чтобы писалось? да? ага
0 |
4 / 4 / 3 Регистрация: 06.05.2015 Сообщений: 93 |
|
11.08.2015, 10:13 |
5 |
РешениеArturKaktus, вам ниже пример показали, все что вы забыли это «+=»
1 |
ArturKaktus 3 / 3 / 3 Регистрация: 21.10.2014 Сообщений: 113 |
||||||||
11.08.2015, 10:17 [ТС] |
6 |
|||||||
хм, странно.. решил аллюзией отделаться, но не получилось.
есть два multiline textbox: в одном каждое слово в каждом строке. надо через for пропустить все слова, чтобы так же каждое слово через строку. Странно что твой пример работает, а тут нет p.s. все, увидил причину, спасибо. не проснулся с ночи(
0 |
Последнее обновление: 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; } }
The «Lines» property of a TextBox is an array of strings. By definition, you cannot add elements to an existing string[]
, like you can to a List<string>
. There is simply no method available for the purpose. You must instead create a new string[]
based on the current Lines reference, and assign it to Lines.
Using a little Linq (.NET 3.5 or later):
textBox1.Lines = textBox.Lines.Concat(new[]{"Some Text"}).ToArray();
This code is fine for adding one new line at a time based on user interaction, but for initializing a textbox with a few dozen new lines, it will perform very poorly. If you’re setting the initial value of a TextBox, I would either set the Text property directly using a StringBuilder (as other answers have mentioned), or if you’re set on manipulating the Lines property, use a List to compile the collection of values and then convert it to an array to assign to Lines:
var myLines = new List<string>();
myLines.Add("brown");
myLines.Add("brwn");
myLines.Add("brn");
myLines.Add("brow");
myLines.Add("br");
myLines.Add("brw");
...
textBox1.Lines = myLines.ToArray();
Even then, because the Lines array is a calculated property, this involves a lot of unnecessary conversion behind the scenes.
The «Lines» property of a TextBox is an array of strings. By definition, you cannot add elements to an existing string[]
, like you can to a List<string>
. There is simply no method available for the purpose. You must instead create a new string[]
based on the current Lines reference, and assign it to Lines.
Using a little Linq (.NET 3.5 or later):
textBox1.Lines = textBox.Lines.Concat(new[]{"Some Text"}).ToArray();
This code is fine for adding one new line at a time based on user interaction, but for initializing a textbox with a few dozen new lines, it will perform very poorly. If you’re setting the initial value of a TextBox, I would either set the Text property directly using a StringBuilder (as other answers have mentioned), or if you’re set on manipulating the Lines property, use a List to compile the collection of values and then convert it to an array to assign to Lines:
var myLines = new List<string>();
myLines.Add("brown");
myLines.Add("brwn");
myLines.Add("brn");
myLines.Add("brow");
myLines.Add("br");
myLines.Add("brw");
...
textBox1.Lines = myLines.ToArray();
Even then, because the Lines array is a calculated property, this involves a lot of unnecessary conversion behind the scenes.
- HowTo
- C# Howtos
- TextBox New Line in C#

This tutorial will discuss the method to add a new line to a text box in C#.
TextBox New Line With the TextBox.Multiline
Property in C#
The TextBox.Multiline
property stores a boolean value in it. The value of the TextBox.Multiline
property determines whether the control is a multiline text box or not. The value of this property can only be true
or false
. The true
value indicates that this specific text box can have multiple lines in it. The false
value indicates that this specific text box cannot have multiple lines in it. The following code example shows us how to add a new line to a text box with the TextBox.Multiline
property in C#.
private void button1_Click(object sender, EventArgs e)
{
string longtext = "This is some text and it is very very long for just one line";
textBox1.Text = longtext;
textBox1.AppendText(Environment.NewLine);
textBox1.Multiline = true;
}
Output:
In the above code, we inserted a very long string to the textBox1
with textBox1.Text = longtext
and added a new line to the textBox1
after that with textBox1.AppendText(Environment.NewLine)
. After that, we specified that the textBox1
is a multiline text box by setting the value of the textBox1.Multiline
property to true
.
Maisam is a highly skilled and motivated Data Scientist. He has over 4 years of experience with Python programming language. He loves solving complex problems and sharing his results on the internet.