Длина – это атрибут тега «input», который помогает установить размер текстового поля для пользователя. Тег «input» является основным тегом, когда дело доходит до создания пользовательских форм на HTML. Чтобы создать определенную часть формы с помощью тега «input», нужно правильно определить атрибут. Например, с помощью атрибутов тега «input» можно создать следующие поля:
пункт для ввода текста, где можно собирать фамилию, имя, отчество или короткое сообщение пользователя;
пункт для ввода пароля;
открыть пользователям возможность выбирать пункты радио-списка;
открыть пользователям возможность проводить множественный выбор из списка чекбокса;
скрытые поля, которые появляются только при определенных условиях;
разнообразные кнопки, в том числе и кнопки для отправки формы, очистки формы;
и др.
В HTML5 у тега «input» насчитывается несколько десятков разнообразных атрибутов, которые помогают создавать разнообразные поля. Тег «input» в основном используется внутри тега «form», однако в HTML5 он приобрел самостоятельность и может применяться отдельно.
Разнообразие атрибутов тега «input» велико. Поэтому, постепенно, в своих статьях мы будем рассказывать о каждом. Сегодня мы подробнее остановимся на атрибуте, определяющем текстовое поле формы и подробнее расскажем, что такое длина или размер «input».
Атрибут текстового поля: длина «input»
Важнейшим атрибутом у тега «input» является «type». Именно он определяет какое поле будет перед нами: текстовое, для пароля, чекбокс, радио и др. Поэтому, чтобы определить тег «input», как текстовое поле нужно воспользоваться вот таким синтаксисом:
<input type=»text»/>
Обозначив тег «input» таким образом мы получим текстовое поле в форме, но оно будет с «гибким» размером. То есть, оно растянется на всю ширину контейнера, в котором мы обозначили тег «input». Такой подход не всегда уместен. Иногда нам нужно чтобы текстовое поле было определенного размера. Мы можем это сделать, если задействовать CSS-свойство «width» для конкретного поля «input» или прямо внутри самого тега мы можем задействовать свойство «size». В свойстве «size» нужно прописать какое-то число, где число будет определять ширину поля, а обозначать количество видимых символов.
Кстати, когда говорят «длина input» – это немного не корректное высказывание, потому что правильнее будет говорить «ширина input» или «размер input».
Как выставляется ширина(длина, размер) «input» в HTML на примере
Давайте сверстаем небольшую HTML-форму, где у нас будет текстовое поле «input» заданной ширины. Код будет вот таким:
<!DOCTYPE html>
<html>
<head>
<metacharset=»utf-8″>
<title>Ширина текстового поля</title>
<style>
#userForm {
width: 600px; /*Определяем пиксельную ширину текстового поля с помощью CSS-свойств */
}
</style>
</head>
<body>
<form method=»post» action=»myhandler.php»>
<p>Введите ваше имя:</p>
<p><input type=»text» name=»usernameform» id=»userForm» size=»55″ />
<input type=»submit» name=»SubmitForm» value=»Послать» /></p>
</form>
</body>
</html>
Результат этой формы можно увидеть на рисунке ниже:
Важно отметить, что размер текстового поля «input» в CSS-свойствах можно определить разными единицами измерения: в пикселях, процентах и других измерительных единицах. А в свойстве «size» можно указать только количество видимых текстовых символов в виде числа. На примере, что мы привели выше, мы указали оба варианта определения размера поля «input». На практике так делать не надо, потому что в этом случае сработает только CSS-свойство, так как оно по иерархии главнее, чем внутреннее свойство «size».
Заключение
Сегодня мы рассказали, что длина, ширина и размер текстового поля «input» в HTML – это определения одного и того же свойства и правильно его называть «ширина input». На примере мы показали, что установить размер текстового поля всегда можно при помощи CSS-свойства «width», либо использовать внутреннее свойства текстового поля «input» – «size».
При оформлении документов в текстовом редакторе Word очень часто возникает необходимость изменить размеры полей. Иногда это необходимо для соблюдения технических требований к документу, а иногда просто для красивого внешнего вида.
В текстовом редакторе Word присутствует несколько стандартных размеров полей, которые пользователь может выбрать при создании документа. Кроме этого, есть возможность сделать собственные размеры, если ни один из стандартных вариантов не подходит. Главное помнить, что слишком узкие поля могут создать проблемы при распечатке такого документа на принтере.
В этом материале мы рассмотрим все доступные способы, которые можно использовать для изменения полей в документе Word. Материал будет актуален для всех последних версий Word, включая Word 2007, 2010, 2013, 2016 и 2019.
Выбор размера полей из стандартного списка
В текстовом редакторе Word есть несколько способов изменения размера полей. Самый простой вариант, это выбрать подходящий размер из списка предложенных. Для этого нужно открыть вкладку «Макет» (или вкладку «Разметка страницы» если у вас старая версия программы) и нажать на кнопку «Поля», которая находится в левой верхней части окна.
После нажатия на кнопку «Поля» откроется список стандартных размеров полей. Здесь доступны такие варианты как: обычные, узкие, средние, широкие и зеркальные поля. Также здесь можно выбрать «Последние пользовательские поля», которые повторяют последние настройки пользователя, а также «Настраиваемые поля», но их мы рассмотрим позже.
Итак, основными размерами полей, которые здесь доступны, являются:
- Обычные – стандартный размер, используется программой Word по умолчанию. Данные поля отступают 2 см. сверху, 2 см. снизу, 3 см. слева и 1.5 см. справа.
- Узкие – минимальный размер, данные поля со всех сторон страницы отступают по 1.27 см.
- Средние – средний размер, данные поля отступают 2.54 см. сверху, 2.54 см. снизу, 1.91 см. слева и 1.91 см справа.
- Широкие – максимальный размер, данные поля отступают 2.54 см. сверху, 2.54 см. снизу, 5.08 см. слева и 5.08 см. справа.
- Зеркальные – поля с одинаковым отступом от правого и левого края страницы, применяются для печати документа в виде книги. Данные поля отступают 2.54 см. сверху, 2.54 см. снизу, 3.18 см с внутренней стороны страницы и 2.54 см. с внешней стороны страницы.
Для того чтобы изменить текущий размер полей на один из предложенных вариантов нужно просто выбрать его в данном списке. После этого поля страницы будут автоматически изменены согласно выбранным настройкам.
Как сделать собственный размер полей
При оформлении рефератов, курсовых и дипломных работ, а также других технических документов, необходимо четко соблюдать правила. В частности, нужно использовать определенный заранее установленный размер полей. В таких случаях стандартные размеры, которые предлагает тактовый редактор Word, не подходят.
Если вы столкнулись с подобной задачей, то вам нужно перейти на вкладку «Макет» (или «Разметка страницы»), нажать на кнопку «Поля» и выбрать вариант «Настраиваемые поля».
После выбора данного пункта меню перед вами откроется окно «Параметры страницы». В данном окне сосредоточены все основные настройки, которые касаются размеров страницы. Среди прочего здесь можно изменять размеры полей. Для этого нужно перейти на вкладку «Поля» и воспользоваться опциями в верхней части окна. Здесь можно указать необходимый отступ для верхнего, нижнего, левого и правого края листа.
Также здесь можно изменить размер дополнительных отступов, которые используются для переплета документа. Эти опции называются «Переплет» и «Положение переплета».
Обратите внимание, если вы используете опции «Зеркальные поля», «2 страницы на листе» или «Брошюра», то параметр «Положение переплета» может быть заблокирован и определяться исключительно редактором Word.
Как изменять поля с помощью линейки
Если вам приходится часто изменять размеры полей в Ворде, то это можно делать при помощи инструмента «Линейка». Этот инструмент позволяет быстро редактировать поля страницы, не переключаясь между вкладками и не открывая никаких окон.
Чтобы воспользоваться этим вариантом нужно прейти на вкладку «Вид» и включить там инструмент «Линейка». После этого сверху и слева от листа будет отображаться линейка, с помощью которой можно будет изменять поля.
Иногда линейка появляется только вверху страницы. В этом случае нужно открыть меню «Файл», зайти в «Параметры – Дополнительно» и активировать функцию показа вертикальной линейки.
После того как линейка включена, поля страницы можно изменять практически в один клик.
Для этого достаточно просто навести мышку на край поля на линейке (отмечено серым цветом), нажать на него левой кнопкой мышки и перетащить в нужную сторону.
Посмотрите также:
- Как перевернуть страницу в Word
- Как построить график в Excel
- Как сделать альбомную страницу в Word
- Как сделать вертикальный текст в Word
- Как закрепить область в Экселе
Автор
Александр Степушин
Создатель сайта comp-security.net, автор более 2000 статей о ремонте компьютеров, работе с программами, настройке операционных систем.
Остались вопросы?
Задайте вопрос в комментариях под статьей или на странице
«Задать вопрос»
и вы обязательно получите ответ.
How do I change the height of a textbox ?
Neither of the below work:
this.TextBox1.Size = new System.Drawing.Size(173, 100);
or
this.TextBox1.Size.Height = 100;
I wanted to be able to change the single line text box height to fit a font size on it without using multi-line if possible.
asked May 2, 2011 at 2:41
0
Go into yourForm.Designer.cs
Scroll down to your textbox. Example below is for textBox2 object.
Add this
this.textBox2.AutoSize = false;
and set its size to whatever you want
this.textBox2.Size = new System.Drawing.Size(142, 27);
Will work like a charm — without setting multiline to true, but only until you change any option in designer itself (you will have to set these 2 lines again).
I think, this method is still better than multilining. I had a textbox for nickname in my app and with multiline, people sometimes accidentially wrote their names twice, like ThomasnThomas (you saw only one in actual textbox line). With this solution, text is simply hiding to the left after each char too long for width, so its much safer for users, to put inputs.
answered Jun 26, 2013 at 17:32
3
There are two ways to do this :
- Set the textbox’s «multiline» property to true, in this case you don’t want to do it so;
- Set a bigger font size to the textbox
I believe it is the only ways to do it; the bigger font size should automatically fit with the textbox
answered May 2, 2011 at 2:45
MrRoyMrRoy
1,12510 silver badges9 bronze badges
1
You can set the MinimumSize
and/or the MaximumSize
properties of the textbox. This does not affect the size immediately, but when you resize the textbox in the forms designer, the size will automatically be adjusted to satisfy the minimum/maximum size constraints. This works even when Multiline
is set to false
and does not depend on the font size.
answered Feb 28, 2013 at 15:32
4
Just found a great little trick to setting a custom height to a textbox.
In the designer view, set the minimumSize
to whatever you desire, and then completely remove the size
setting. This will cause the designer to update with the new minimum settings!
answered Nov 6, 2014 at 11:48
2
set the minimum size property
tb_01.MinimumSize = new Size(500, 300);
This is working for me.
answered Oct 31, 2012 at 3:55
LazyZebraLazyZebra
1,08916 silver badges24 bronze badges
Try the following
textBox1.Multiline = true;
textBox1.Height = 100;
textBox1.Width = 173;
answered May 4, 2011 at 6:03
RaufRauf
12.2k19 gold badges76 silver badges124 bronze badges
Steps:
- Set the textboxes to multiline
- Change the height
- Change the font size. (so it fit into the big textboxes)
- Set the textboxes back to non-multiline
answered Mar 21, 2017 at 15:44
1
public partial class MyTextBox : TextBox
{
[DefaultValue(false)]
[Browsable(true)]
public override bool AutoSize
{
get
{
return base.AutoSize;
}
set
{
base.AutoSize = value;
}
}
public MyTextBox()
{
InitializeComponent();
this.AutoSize = false;
}
}
aschipfl
33.1k12 gold badges53 silver badges94 bronze badges
answered May 28, 2014 at 4:48
May be it´s a little late. But you can do this.
txtFoo.Multiline = true;
txtFoo.MinimumSize = new Size(someWith,someHeight);
I solved it that way.
answered May 11, 2011 at 15:43
AutoSize, Minimum, Maximum does not give flexibility. Use multiline and handle the enter key event and suppress the keypress. Works great.
textBox1.Multiline = true;
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
e.Handled = true;
e.SuppressKeyPress = true;
}
}
answered Apr 10, 2014 at 20:37
pilipili
7752 gold badges10 silver badges24 bronze badges
1
You can put it inside a panel that has the same back color with your desired height. This way has this advantage that the text box can center horizontally, which is not provided by other solutions.
You can make it even more natural by using the following methods
private void textBox1_Enter(object sender, EventArgs e)
{
panelTextBox.BorderStyle = BorderStyle.FixedSingle;
}
private void textBox1_Leave(object sender, EventArgs e)
{
panelTextBox.BorderStyle = BorderStyle.None;
}
answered Dec 26, 2015 at 7:59
AhmadAhmad
8,2799 gold badges71 silver badges124 bronze badges
The Simplest Way to do that
- Right click on the TextBox.
- Go to properties.
- Set Multiline = True.
Now you will be able to resize the TextBox vertically as you wish.
Joel
3793 silver badges14 bronze badges
answered Feb 2, 2018 at 8:05
ArunPratapArunPratap
4,5987 gold badges28 silver badges43 bronze badges
for me, the best approach is remove border of the textbox, and place it inside a Panel, which can be customized as you like.
answered Dec 25, 2012 at 22:43
1
The following code added in your constructor after calling InitializeComponent() will make it possible to programmatically set your text box to the correct height without a) changing the Multiline property, b) having to hardcode a height, or c) mucking with the Designer-generated code. It still isn’t necessarily as clean or nice as doing it in a custom control, but it’s fairly simple and robust:
if (txtbox.BorderStyle == BorderStyle.None)
{
txtbox.BorderStyle = BorderStyle.FixedSingle;
var heightWithBorder = txtbox.ClientRectangle.Height;
txtbox.BorderStyle = BorderStyle.None;
txtbox.AutoSize = false;
txtbox.Height = heightWithBorder;
}
I decided to make it cleaner and easier to use by putting it in a static class and make it an extension method on TextBox:
public static class TextBoxExtensions
{
public static void CorrectHeight(this TextBox txtbox)
{
if (txtbox.BorderStyle == BorderStyle.None)
{
txtbox.BorderStyle = BorderStyle.FixedSingle;
var heightWithBorder = txtbox.ClientRectangle.Height;
txtbox.BorderStyle = BorderStyle.None;
txtbox.AutoSize = false;
txtbox.Height = heightWithBorder;
}
}
}
answered Feb 2, 2015 at 16:28
Tom BogleTom Bogle
4364 silver badges18 bronze badges
0
Some of you were close but changing designer code like that is annoying because you always have to go back and change it again.
The original OP was likely using an older version of .net because version 4 autosizes the textbox height to fit the font, but does not size comboboxes and textboxes the same which is a completely different problem but drew me here.
This is the problem I faced when placing textboxes next to comboboxes on a form. This is a bit irritating because who wants two controls side-by-side with different heights? Or different fonts to force heights? Step it up Microsoft, this should be simple!
I’m using .net framework 4 in VS2012 and the following was the simplest solution for me.
In the form load event (or anywhere as long as fired after InitializeComponent
): textbox.AutoSize = false
Then set the height to whatever you want. For me I wanted my text boxes and combo boxes to be the same height so textbox.height = combobox.height
did the trick for me.
Notes:
1) The designer will not be affected so it will require you to start your project to see the end result, so there may be some trial and error.
2) Align the tops of your comboboxes and textboxes if you want them to be aligned properly after the resize because the textboxes will grow down.
answered Dec 1, 2016 at 16:06
JoeMiloJoeMilo
1231 silver badge10 bronze badges
1
This is what worked nicely for me since all I wanted to do was set the height of the textbox. The property is Read-Only and the property is in the Unit class so you can’t just set it. So I just created a new Unit and the constructor lets me set the height, then set the textbox to that unit instead.
Unit height = txtTextBox.Height;
double oldHeight = height.Value;
double newHeight = height.Value + 20; //Added 20 pixels
Unit newHeightUnit = new Unit(newHeight);
txtTextBox.Height = newHeightUnit;
answered Mar 29, 2017 at 19:13
IQtheMCIQtheMC
2012 silver badges11 bronze badges
You can make multiline : false
and then just change the text size on the text box then the height will automatically increment
answered Jul 14, 2021 at 19:49
you can also change you can also change MinimumSize
answered Apr 9, 2019 at 6:28
NanduNandu
1039 bronze badges
So after having the same issue with not being able to adjust height in text box, Width adjustment is fine but height never adjusted with the above suggestions (at least for me), I was finally able to take make it happen. As mentioned above, the issue appeared to be centered around a default font size setting in my text box and the behavior of the text box auto sizing around it. The default font size was tiny. Hence why trying to force the height or even turn off autosizing failed to fix the issue for me.
Set the Font properties to the size of your liking and then height change will kick in around the FONT size, automatically. You can still manually set your text box width. Below is snippet I added that worked for me.
$textBox = New-Object System.Windows.Forms.TextBox
$textBox.Location = New-Object System.Drawing.Point(60,300)
$textBox.Size = New-Object System.Drawing.Size(600,80)
$textBox.Font = New-Object System.Drawing.Font("Times New Roman",18,[System.Drawing.FontStyle]::Regular)
$textBox.Form.Font = $textbox.Font
Please note the Height value in ‘$textBox.Size = New-Object System.Drawing.Size(600,80)’ is being ignored and the FONT size is actually controlling the height of the text box by autosizing around that font size.
answered Apr 14, 2019 at 3:34
All you have to do is enable the multiline in the properties window, put the size you want in that same window and then in your .cs after the InitializeComponent put txtexample.Multiline = false; and so the multiline is not enabled but the size of the txt is as you put it.
InitializeComponent();
txtEmail.Multiline = false;
txtPassword.Multiline = false;
answered Jul 1, 2019 at 3:44
1
I think this should work.
TextBox1.Height = 100;
answered May 2, 2011 at 2:48
KaeLKaeL
3,6392 gold badges27 silver badges55 bronze badges
0
How do I change the height of a textbox ?
Neither of the below work:
this.TextBox1.Size = new System.Drawing.Size(173, 100);
or
this.TextBox1.Size.Height = 100;
I wanted to be able to change the single line text box height to fit a font size on it without using multi-line if possible.
asked May 2, 2011 at 2:41
0
Go into yourForm.Designer.cs
Scroll down to your textbox. Example below is for textBox2 object.
Add this
this.textBox2.AutoSize = false;
and set its size to whatever you want
this.textBox2.Size = new System.Drawing.Size(142, 27);
Will work like a charm — without setting multiline to true, but only until you change any option in designer itself (you will have to set these 2 lines again).
I think, this method is still better than multilining. I had a textbox for nickname in my app and with multiline, people sometimes accidentially wrote their names twice, like ThomasnThomas (you saw only one in actual textbox line). With this solution, text is simply hiding to the left after each char too long for width, so its much safer for users, to put inputs.
answered Jun 26, 2013 at 17:32
3
There are two ways to do this :
- Set the textbox’s «multiline» property to true, in this case you don’t want to do it so;
- Set a bigger font size to the textbox
I believe it is the only ways to do it; the bigger font size should automatically fit with the textbox
answered May 2, 2011 at 2:45
MrRoyMrRoy
1,12510 silver badges9 bronze badges
1
You can set the MinimumSize
and/or the MaximumSize
properties of the textbox. This does not affect the size immediately, but when you resize the textbox in the forms designer, the size will automatically be adjusted to satisfy the minimum/maximum size constraints. This works even when Multiline
is set to false
and does not depend on the font size.
answered Feb 28, 2013 at 15:32
4
Just found a great little trick to setting a custom height to a textbox.
In the designer view, set the minimumSize
to whatever you desire, and then completely remove the size
setting. This will cause the designer to update with the new minimum settings!
answered Nov 6, 2014 at 11:48
2
set the minimum size property
tb_01.MinimumSize = new Size(500, 300);
This is working for me.
answered Oct 31, 2012 at 3:55
LazyZebraLazyZebra
1,08916 silver badges24 bronze badges
Try the following
textBox1.Multiline = true;
textBox1.Height = 100;
textBox1.Width = 173;
answered May 4, 2011 at 6:03
RaufRauf
12.2k19 gold badges76 silver badges124 bronze badges
Steps:
- Set the textboxes to multiline
- Change the height
- Change the font size. (so it fit into the big textboxes)
- Set the textboxes back to non-multiline
answered Mar 21, 2017 at 15:44
1
public partial class MyTextBox : TextBox
{
[DefaultValue(false)]
[Browsable(true)]
public override bool AutoSize
{
get
{
return base.AutoSize;
}
set
{
base.AutoSize = value;
}
}
public MyTextBox()
{
InitializeComponent();
this.AutoSize = false;
}
}
aschipfl
33.1k12 gold badges53 silver badges94 bronze badges
answered May 28, 2014 at 4:48
May be it´s a little late. But you can do this.
txtFoo.Multiline = true;
txtFoo.MinimumSize = new Size(someWith,someHeight);
I solved it that way.
answered May 11, 2011 at 15:43
AutoSize, Minimum, Maximum does not give flexibility. Use multiline and handle the enter key event and suppress the keypress. Works great.
textBox1.Multiline = true;
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
e.Handled = true;
e.SuppressKeyPress = true;
}
}
answered Apr 10, 2014 at 20:37
pilipili
7752 gold badges10 silver badges24 bronze badges
1
You can put it inside a panel that has the same back color with your desired height. This way has this advantage that the text box can center horizontally, which is not provided by other solutions.
You can make it even more natural by using the following methods
private void textBox1_Enter(object sender, EventArgs e)
{
panelTextBox.BorderStyle = BorderStyle.FixedSingle;
}
private void textBox1_Leave(object sender, EventArgs e)
{
panelTextBox.BorderStyle = BorderStyle.None;
}
answered Dec 26, 2015 at 7:59
AhmadAhmad
8,2799 gold badges71 silver badges124 bronze badges
The Simplest Way to do that
- Right click on the TextBox.
- Go to properties.
- Set Multiline = True.
Now you will be able to resize the TextBox vertically as you wish.
Joel
3793 silver badges14 bronze badges
answered Feb 2, 2018 at 8:05
ArunPratapArunPratap
4,5987 gold badges28 silver badges43 bronze badges
for me, the best approach is remove border of the textbox, and place it inside a Panel, which can be customized as you like.
answered Dec 25, 2012 at 22:43
1
The following code added in your constructor after calling InitializeComponent() will make it possible to programmatically set your text box to the correct height without a) changing the Multiline property, b) having to hardcode a height, or c) mucking with the Designer-generated code. It still isn’t necessarily as clean or nice as doing it in a custom control, but it’s fairly simple and robust:
if (txtbox.BorderStyle == BorderStyle.None)
{
txtbox.BorderStyle = BorderStyle.FixedSingle;
var heightWithBorder = txtbox.ClientRectangle.Height;
txtbox.BorderStyle = BorderStyle.None;
txtbox.AutoSize = false;
txtbox.Height = heightWithBorder;
}
I decided to make it cleaner and easier to use by putting it in a static class and make it an extension method on TextBox:
public static class TextBoxExtensions
{
public static void CorrectHeight(this TextBox txtbox)
{
if (txtbox.BorderStyle == BorderStyle.None)
{
txtbox.BorderStyle = BorderStyle.FixedSingle;
var heightWithBorder = txtbox.ClientRectangle.Height;
txtbox.BorderStyle = BorderStyle.None;
txtbox.AutoSize = false;
txtbox.Height = heightWithBorder;
}
}
}
answered Feb 2, 2015 at 16:28
Tom BogleTom Bogle
4364 silver badges18 bronze badges
0
Some of you were close but changing designer code like that is annoying because you always have to go back and change it again.
The original OP was likely using an older version of .net because version 4 autosizes the textbox height to fit the font, but does not size comboboxes and textboxes the same which is a completely different problem but drew me here.
This is the problem I faced when placing textboxes next to comboboxes on a form. This is a bit irritating because who wants two controls side-by-side with different heights? Or different fonts to force heights? Step it up Microsoft, this should be simple!
I’m using .net framework 4 in VS2012 and the following was the simplest solution for me.
In the form load event (or anywhere as long as fired after InitializeComponent
): textbox.AutoSize = false
Then set the height to whatever you want. For me I wanted my text boxes and combo boxes to be the same height so textbox.height = combobox.height
did the trick for me.
Notes:
1) The designer will not be affected so it will require you to start your project to see the end result, so there may be some trial and error.
2) Align the tops of your comboboxes and textboxes if you want them to be aligned properly after the resize because the textboxes will grow down.
answered Dec 1, 2016 at 16:06
JoeMiloJoeMilo
1231 silver badge10 bronze badges
1
This is what worked nicely for me since all I wanted to do was set the height of the textbox. The property is Read-Only and the property is in the Unit class so you can’t just set it. So I just created a new Unit and the constructor lets me set the height, then set the textbox to that unit instead.
Unit height = txtTextBox.Height;
double oldHeight = height.Value;
double newHeight = height.Value + 20; //Added 20 pixels
Unit newHeightUnit = new Unit(newHeight);
txtTextBox.Height = newHeightUnit;
answered Mar 29, 2017 at 19:13
IQtheMCIQtheMC
2012 silver badges11 bronze badges
You can make multiline : false
and then just change the text size on the text box then the height will automatically increment
answered Jul 14, 2021 at 19:49
you can also change you can also change MinimumSize
answered Apr 9, 2019 at 6:28
NanduNandu
1039 bronze badges
So after having the same issue with not being able to adjust height in text box, Width adjustment is fine but height never adjusted with the above suggestions (at least for me), I was finally able to take make it happen. As mentioned above, the issue appeared to be centered around a default font size setting in my text box and the behavior of the text box auto sizing around it. The default font size was tiny. Hence why trying to force the height or even turn off autosizing failed to fix the issue for me.
Set the Font properties to the size of your liking and then height change will kick in around the FONT size, automatically. You can still manually set your text box width. Below is snippet I added that worked for me.
$textBox = New-Object System.Windows.Forms.TextBox
$textBox.Location = New-Object System.Drawing.Point(60,300)
$textBox.Size = New-Object System.Drawing.Size(600,80)
$textBox.Font = New-Object System.Drawing.Font("Times New Roman",18,[System.Drawing.FontStyle]::Regular)
$textBox.Form.Font = $textbox.Font
Please note the Height value in ‘$textBox.Size = New-Object System.Drawing.Size(600,80)’ is being ignored and the FONT size is actually controlling the height of the text box by autosizing around that font size.
answered Apr 14, 2019 at 3:34
All you have to do is enable the multiline in the properties window, put the size you want in that same window and then in your .cs after the InitializeComponent put txtexample.Multiline = false; and so the multiline is not enabled but the size of the txt is as you put it.
InitializeComponent();
txtEmail.Multiline = false;
txtPassword.Multiline = false;
answered Jul 1, 2019 at 3:44
1
I think this should work.
TextBox1.Height = 100;
answered May 2, 2011 at 2:48
KaeLKaeL
3,6392 gold badges27 silver badges55 bronze badges
0