626 / 433 / 45 Регистрация: 10.03.2012 Сообщений: 3,082 |
|
1 |
|
Увеличение шрифта на форме18.05.2014, 17:15. Показов 22540. Ответов 8
Как увеличить размере текста полученного на форме?
0 |
0 / 0 / 1 Регистрация: 18.05.2014 Сообщений: 9 |
|
18.05.2014, 21:21 |
2 |
0 |
626 / 433 / 45 Регистрация: 10.03.2012 Сообщений: 3,082 |
|
18.05.2014, 21:26 [ТС] |
3 |
KainRA, Текст программно создается
0 |
5459 / 4232 / 1208 Регистрация: 12.10.2013 Сообщений: 12,223 Записей в блоге: 2 |
|
18.05.2014, 21:30 |
4 |
Invincible, уточните задачу. Текст расположен прямо на форме? В какой момент должно произойти изменение? Выпадающий список расположен на форме?
0 |
BadEvgen 25 / 25 / 8 Регистрация: 30.04.2013 Сообщений: 79 |
||||
18.05.2014, 21:47 |
5 |
|||
Если текст размещен на элементе (label, textBox и т.д.) то нужно изменять его размер в свойствах элмента. Например:
Но будет изменяться размер Label и форма может поплыть, для того чтобы этого избежать просто задайте максимальные границы размера элемента. Увидел Вашу фотографию, посмотрите в сторону презгрузки конструктора класса Font, там можно задать стиль (подчеркнуты, жирный и т.д.)
0 |
insite2012 5459 / 4232 / 1208 Регистрация: 12.10.2013 Сообщений: 12,223 Записей в блоге: 2 |
||||
18.05.2014, 21:54 |
6 |
|||
Вот. На форме кнопка, комбобокс и лейбл (лейбл для проверки).
0 |
25 / 25 / 8 Регистрация: 30.04.2013 Сообщений: 79 |
|
18.05.2014, 22:12 |
7 |
А почему размер присваивается по SelectedIndex, а не SelectedItem? Как здесь цитировать или отвечать?( Не могу никак найти(
0 |
5459 / 4232 / 1208 Регистрация: 12.10.2013 Сообщений: 12,223 Записей в блоге: 2 |
|
18.05.2014, 22:36 |
8 |
BadEvgen, в данном случае это не важно.
0 |
Whitecolor 626 / 433 / 45 Регистрация: 10.03.2012 Сообщений: 3,082 |
||||||||
20.05.2014, 14:45 [ТС] |
9 |
|||||||
Подскажите, как можно сделать,чтобы после запуска программы, можно было увеличивать и уменьшать шрифт
0 |
- Remove From My Forums
-
Question
-
hi
i have label control in my windows form, sometimes the output that i want to set as the text property for the label is too long. how i can change the font size of the label in code??
thanks
Answers
-
label1.Font = new Font(label1.Font.FontFamily, 13);
Hans Passant.
-
Marked as answer by
FMZL
Sunday, September 27, 2009 9:20 AM
-
Marked as answer by
All replies
-
Set the Font property. Doh.
Hans Passant.
-
I know i can change it in designer through Font property but i dont know how to do it in code. Label.Font.Size property it a read-only. if you know tell me how?
-
label1.Font = new Font(label1.Font.FontFamily, 13);
Hans Passant.
-
Marked as answer by
FMZL
Sunday, September 27, 2009 9:20 AM
-
Marked as answer by
Improve Article
Save Article
Improve Article
Save Article
In Windows Forms, Label control is used to display text on the form and it does not take part in user input or in mouse or keyboard events. You are allowed to set the size of Label control using Size Property. You can set this property using two different methods:
1. Design-Time: It is the easiest method to set the Size property of the Label control using the following steps:
- Step 1: Create a windows form as shown in the below image:
Visual Studio -> File -> New -> Project -> WindowsFormApp - Step 2: Drag the Label control from the ToolBox and drop it on the windows form. You are allowed to place a Label control anywhere on the windows form according to your need.
- Step 3: After drag and drop you will go to the properties of the Label control to set the Size property of the Label.
Output:
2. Run-Time: It is a little bit trickier than the above method. In this method, you can set the size of the Label control programmatically with the help of given syntax:
public System.Drawing.Size Size { get; set; }
Here, Size indicates the height and the width of the Label in pixel. Following steps are used to set the Size property of the Label:
- Step 1: Create a label using the Label() constructor is provided by the Label class.
// Creating label using Label class Label mylab = new Label();
- Step 2: After creating Label, set the Size property of the Label provided by the Label class.
// Set Size property of the label mylab.Size = new Size(120, 25);
- Step 3: And last add this Label control to form using Add() method.
// Add this label to the form this.Controls.Add(mylab);
Example:
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
WindowsFormsApp16 {
public
partial
class
Form1 : Form {
public
Form1()
{
InitializeComponent();
}
private
void
Form1_Load(
object
sender, EventArgs e)
{
Label mylab =
new
Label();
mylab.Text =
"GeeksforGeeks"
;
mylab.Location =
new
Point(222, 90);
mylab.Size =
new
Size(120, 25);
mylab.BorderStyle = BorderStyle.FixedSingle;
this
.Controls.Add(mylab);
}
}
}
Output:
Практическое руководство. Приведение размера элемента управления Label в соответствие с его содержимым в Windows Forms
Элемент управления Windows Forms Label может быть однострочным или многострочным, он может быть фиксированным по размеру либо автоматически изменять размер в соответствии с заголовком. Свойство AutoSize помогает менять размер элементов управления в соответствии с размером заголовка, что особенно полезно, если заголовок меняется во время выполнения.
Динамическое изменение размера элемента управления меткой в соответствии с его содержимым
- Для его свойства AutoSize задайте значение true .
Если для AutoSize задано значение false , слова, указанные в свойстве Text, переносятся на следующую строку, если это возможно, но элемент управления не будет увеличиваться.
Профиль
Группа: Участник
Сообщений: 16
Регистрация: 11.8.2009
Репутация: нет
Всего: нет
Мне надо в ходе программы изменить размер шрифта Label’а, а Visual Studio 2005 говорит, что параметр Label.Font.Size доступен только для чтения. Как тут быть?
Профиль
Группа: Участник
Сообщений: 523
Регистрация: 18.1.2008
Репутация: нет
Всего: 15
А в 2005 разве не так
Код |
Label1.FontSize = 30 |
Профиль
Группа: Участник
Сообщений: 16
Регистрация: 11.8.2009
Репутация: нет
Всего: нет
Профиль
Группа: Участник
Сообщений: 16
Регистрация: 11.8.2009
Репутация: нет
Всего: нет
Вся проблема в том, что число в Label’е не помещается в заданном пространстве и «лезет» на соседние кнопки. Изменить дизайн нельзя, поменять шрифт заранее на маленький тоже нельзя, а мне надо сделать примерно следующее:
Код |
If TextBox.Text > 999999 Then Label.Font.Size = 35 End If |
А как я говорил, параметр Label.Font.Size доступен только для чтения.
Профиль
Группа: Модератор
Сообщений: 20516
Регистрация: 8.4.2004
Где: Зеленоград
Репутация: 1
Всего: 453
О(б)суждение моих действий — в соответствующей теме, пожалуйста. Или в РМ. И высшая инстанция — Администрация форума.
Профиль
Группа: Модератор
Сообщений: 20516
Регистрация: 8.4.2004
Где: Зеленоград
Репутация: 1
Всего: 453
О(б)суждение моих действий — в соответствующей теме, пожалуйста. Или в РМ. И высшая инстанция — Администрация форума.
Доктор Зло(диагност, настоящий, с лицензией и полномочиями)
Профиль
Группа: Модератор
Сообщений: 5817
Регистрация: 14.8.2008
Где: В Коньфпольте
Репутация: 8
Всего: 141
Профиль
Группа: Участник
Сообщений: 16
Регистрация: 11.8.2009
Репутация: нет
Всего: нет
Доктор Зло(диагност, настоящий, с лицензией и полномочиями)
Профиль
Группа: Модератор
Сообщений: 5817
Регистрация: 14.8.2008
Где: В Коньфпольте
Репутация: 8
Всего: 141
Код |
Label1.Font = New Font(Label1.Font.FontFamily, Label1.Font.Size / 2) |
Профиль
Группа: Участник
Сообщений: 16
Регистрация: 11.8.2009
Репутация: нет
Всего: нет
- Прежде чем задать вопрос, воспользуйтесь поиском: возможно Ваш вопрос уже обсуждался и на него был получен ответ.
- Если такой же вопрос не найден, не стоит задавать свой вопрос в любую тему, создайте новую.
- Заголовок темы должен отображать ее суть.
- Содержание поста должно описывать проблему понятно, но в то же время, по возможности, лаконично. Сначала следует описать суть вопроса, потом можно привести пример кода, не вынуждайте других участников угадывать в чем Ваша проблема — телепатов здесь нет.
- Будьте взаимно вежливы и дружелюбны.
- При оформлении сообщений используйте форматирование, примеры кода заключайте в теги [CODE=vbnet][/CODE].
- Также ознакомьтесь с общими правилами, действующими на всем форуме.
- Если вопрос решен, не забывайте помечать тему решенной(вверху темы есть ссылка). Кроме того, если Вы хотите отблагодарить участников, оказавших помощь в решении, можно повысить им репутацию, в случае, если у Вас менее 100 сообщений в форуме и функция изменения репутации Вам недоступна, можете написать сюда.
- Общие вопросы по программированию на платформе .NET обсуждаются здесь.
- Литература по VB .NET обсуждается здесь.
Если Вам помогли и атмосфера форума Вам понравилась, то заходите к нам чаще! С уважением, diadiavova.
0 Пользователей читают эту тему (0 Гостей и 0 Скрытых Пользователей) |
0 Пользователей: |
« Предыдущая тема | VB .NET | Следующая тема » |
[ Время генерации скрипта: 0.1514 ] [ Использовано запросов: 21 ] [ GZIP включён ]
Как изменить размер Label, Visual C#?
является бессмысленной, так как есть она, нет ее, стоит ли там 50,50 или 500,500, при исполнении программы размер текста по факту не меняется. Что делать?
В свойствах нужно найти Autosize и выбрать False)
Всё ещё ищете ответ? Посмотрите другие вопросы с метками c# winforms или задайте свой вопрос.
Site design / logo © 2022 Stack Exchange Inc; user contributions licensed under cc by-sa. rev 2022.6.10.42345
Нажимая «Принять все файлы cookie», вы соглашаетесь, что Stack Exchange может хранить файлы cookie на вашем устройстве и раскрывать информацию в соответствии с нашей Политикой в отношении файлов cookie.
Можно
изменить размер отдельных элементов
управления или набора элементов
управления одного или разных типов,
например, элементов управления Button
(кнопка) и
GroupBox
(группа переключателей).
Чтобы
изменить размер элемента управления
щелкните элемент управления, размер
которого следует изменить, и потяните
за один из восьми маркеров изменения
размера.
Примечание.
Выберите
элемент управления и нажмите клавиши
со стрелками, удерживая нажатой клавишу
SHIFT для изменения размера элемента
управления на одну точку за раз. Нажмите
клавиши со стрелками ВНИЗ или ВПРАВО,
удерживая нажатыми клавиши SHIFT и CTRL,
чтобы изменить размер элемента управления
на большую величину.
Чтобы
изменить размер нескольких элементов
управления в форме
-
Удерживайте
нажатой клавишу CTRL или SHIFT и выберите
элементы управления, размер которых
следует изменить. Для всех элементов
управления используется размер первого
выбранного элемента управления. -
В
меню Формат
выберите Сделать
одного размера
и выберите один из трех параметров: По
ширине, По высоте, Оба. Эти три команды
изменяют размеры элементов управления
так, чтобы они соответствовали размерам
первого выбранного элемента управления.
-
Определение текста, отображаемого элементом управления Windows Forms
На элементах
управления форм Windows Forms обычно отображается
текст, связанный с их основной функцией.
Например, элемент управления Button
(кнопка) обычно имеет заголовок,
указывающий, какое действие выполняется
при нажатии этой кнопки. Для любого
элемента управления можно задавать или
возвращать текст, используя свойство
Text.
Можно изменить шрифт, используя свойство
Font.
Чтобы
задать текст, отображаемый на элементе
управления, программно свойству
Text
присвойте
строковое значение.
Чтобы
создать сочетание клавиш и подчеркнуть
соответствующую ему букву, вставьте
знак & перед этой буквой.
Чтобы
изменить стиль написания текста
программно
для свойства Font
задайте тип объекта Font(«шрифт»,
размер,стиль, единицы измерения размера).
Пример:
Для создания кнопки:
необходимо
прописать
код:
button7.Text
= «&Формат кнопки»;
button7.Font
= new Font(«Monotype Corsiva», 14, FontStyle.Italic,
GraphicsUnit.Point);
-
Определение клавиш доступа для элементов управления Windows Forms
Буква,
используемая в сочетании
клавиш,
подчеркивается в названии меню, в пункте
меню или в метке элемента управления,
например кнопки. С помощью сочетания
клавиш пользователь может «нажать»
кнопку, нажав одновременно клавишу ALT
и клавишу с указанной буквой. Например,
если кнопка запускает процесс печати
формы и ее свойство Text
имеет значение «Print», то можно
добавить амперсанд (&) перед буквой
«P», чтобы эта буква была подчеркнута
в тексте кнопки в режиме выполнения.
Пользователь может выполнить команду,
связанную с кнопкой, нажав сочетание
клавиш ALT+P. Невозможно назначить букву
сочетания клавиш для элемента управления,
который не может получить фокус.
Чтобы
создать букву сочетания клавиш для
элемента управления укажите
в качестве свойства Text
строку, содержащую знак & перед буквой,
которая будет использоваться в сочетании
клавиш, например:
button1.Text = «&Print»;
Соседние файлы в предмете [НЕСОРТИРОВАННОЕ]
- #
- #
- #
- #
- #
- #
- #
- #
- #
- #
- #
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,2779 gold badges70 silver badges123 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,2779 gold badges70 silver badges123 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