Как переименовать форму в windows forms

Asked

Viewed
59k times

I have a quick question. how do I change the name of form1 in my app? whenever I try to use the properties to rename it the form becomes broken and i cant use it anymore. is there a way to change it during run-time or am i doing something wrong with the properties?
thanks.

  • c#
  • winforms

svick's user avatar

svick

237k50 gold badges385 silver badges515 bronze badges

asked Aug 7, 2011 at 2:20

mendez's user avatar

mendezmendez

3173 gold badges7 silver badges14 bronze badges

1

  • Might want to clarify if you want to change either the title (.Text property) or the name (see my answer).

    Aug 7, 2011 at 2:31

6 Answers

If you want to change the text of the window during runtime, use the Text property:

this.Text = "Title";

answered Aug 7, 2011 at 2:33

user807566's user avatar

user807566user807566

2,8283 gold badges20 silver badges27 bronze badges

1

  • Note that this will not work if done before InitializeComponent()

    Nov 14, 2022 at 17:58

Change the Text property of your form under the Properties panel, making sure that you’ve selected the form itself (and not some child control)

enter image description here

answered Aug 7, 2011 at 2:35

foxy's user avatar

foxyfoxy

7,6292 gold badges30 silver badges34 bronze badges

2

  • wow I can’t believe it was that easy lol thanks everyone for the help

    Aug 7, 2011 at 3:18

  • Funny, that the same answer I gave first :)

    Aug 7, 2011 at 3:55

To change the name of your form, select it in the solution explorer and press F2. Then type in the new name for that form (don’t forget the ‘.cs’!) and when you press enter it’ll ask you if you want Visual Studio to update all references to that form. Click Yes, and you’re done.

answered Aug 7, 2011 at 2:30

Only Bolivian Here's user avatar

You can use Form.Text property to get/set the title of the form either in design time or at runtime depending upon your requirement.
If you want to have a dynamic title that changes based on some events you can set it during the runtime for e.g. if you are showing the progress of a task in your form you will want to put the percentage completed in the title.

answered Aug 7, 2011 at 2:33

Gaurav's user avatar

GauravGaurav

8404 silver badges16 bronze badges

answered Aug 7, 2011 at 2:22

hivie7510's user avatar

hivie7510hivie7510

1,24610 silver badges23 bronze badges

1

  • Not sure what happened with the first pasting, but it is fine now. Thanks

    Aug 7, 2011 at 2:34

I believe you can just change the filename of the form to the one you want in design time.

answered Aug 7, 2011 at 2:27

SoftwareGeek's user avatar

SoftwareGeekSoftwareGeek

15.3k19 gold badges62 silver badges78 bronze badges

2

  • You should not do it that way unless you have a trival name such as Form1. If you require a title such as «User Entry Form», then making that the file name would be a bad idea.

    Aug 7, 2011 at 2:35

  • @hivie7510 — agree, it was a simple question that skipped my attention.

    Aug 7, 2011 at 20:51

  • The Overflow Blog
  • Featured on Meta

Related

Hot Network Questions

  • Spacing on text macros

  • Fungus gnats or thrips?

  • Why do some Chinese shows avoid using real toponyms?

  • Who coined the term «signal-to-noise ratio» and when did statisticians start using the term «noise» to describe randomness?

  • Why is the central truss segment of the ISS called S0?

  • Proof the quaternions are 4-dimensional?

  • What is a safe weight for front rack + luggage for a steel race bike fork?

  • Possibility of solar powered space stations around a red dwarf

  • Making a label in QGIS using two different attributes

  • Why does causality imply that the system function is analytic?

  • Applying for a PhD as a disabled person

  • Exact positioning and how easy would it be to recreate this in LaTeX?

  • Meaning of «schon einmal»

  • How to exclude some files and folder in telescope?

  • What would be an appropriate size for an interplanetary bulk cargo ship?

  • Random factorized numbers

  • How to identify transcendental numbers?

  • Business Schengen Visa for Tourism Purpose

  • Will 42.5 in vanity fit in 42 in space?

  • Bad experiences at conferences, worth going anyway?

  • Is every character of the algebra of continuous functions on a locally compact space some evaluation?

  • How can I prove an airline ticket is fake?

  • Can I switch between my two passports from the same country?

  • Typical and minimum ground-pedal clearance

more hot questions

Question feed

Your privacy

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

При создании проектов и форм Windows Forms всегда вверху форм, на месте, где обычно пишется название программы, стоит надпись «Form1» (или  «Form2»,  «Form3» и т.д., в зависимости от количества форм).Так как же сменить эту надоедливую запись на ту, которая нужна нам?

Как переименовать форму Windows Forms в C#

Всё просто. В правом нижнем углу (либо просто с правой стороны в виде полосы) надо найти окно «Свойства». Выглядит оно примерно вот так:

Как переименовать форму Windows Forms в C#

Заметьте, что должна быть выбрана вкладка 2015-02-17 13-19-12 Скриншот экрана.

Если такого окна нет в нашей рабочей области, то его можно открыть, нажав правой кнопкой мыши на форме и выбрав пункт «Свойства».

Как переименовать форму Windows Forms в C#

Итак, мы нашли нашу вкладку, теперь ищем там следующую строку:

Как переименовать форму Windows Forms в C#

Именно свойство «Text» нам и нужно. Оно меняет имя формы. Как видите,напротив него жирным шрифтом написано «Form1». Именно здесь и можно переименовать форму Windows Forms. Стираем его и пишем то, что нам требуется:

Как переименовать форму Windows Forms в C#

Теперь смотрим на нашу форму.

Как переименовать форму Windows Forms в C#

Всё работает! Удачи в освоении C#!

Asked

Viewed
59k times

I have a quick question. how do I change the name of form1 in my app? whenever I try to use the properties to rename it the form becomes broken and i cant use it anymore. is there a way to change it during run-time or am i doing something wrong with the properties?
thanks.

  • c#
  • winforms

svick's user avatar

svick

237k50 gold badges385 silver badges515 bronze badges

asked Aug 7, 2011 at 2:20

mendez's user avatar

mendezmendez

3173 gold badges7 silver badges14 bronze badges

1

  • Might want to clarify if you want to change either the title (.Text property) or the name (see my answer).

    Aug 7, 2011 at 2:31

6 Answers

If you want to change the text of the window during runtime, use the Text property:

this.Text = "Title";

answered Aug 7, 2011 at 2:33

user807566's user avatar

user807566user807566

2,8283 gold badges20 silver badges27 bronze badges

1

  • Note that this will not work if done before InitializeComponent()

    Nov 14, 2022 at 17:58

Change the Text property of your form under the Properties panel, making sure that you’ve selected the form itself (and not some child control)

enter image description here

answered Aug 7, 2011 at 2:35

foxy's user avatar

foxyfoxy

7,6292 gold badges30 silver badges34 bronze badges

2

  • wow I can’t believe it was that easy lol thanks everyone for the help

    Aug 7, 2011 at 3:18

  • Funny, that the same answer I gave first :)

    Aug 7, 2011 at 3:55

To change the name of your form, select it in the solution explorer and press F2. Then type in the new name for that form (don’t forget the ‘.cs’!) and when you press enter it’ll ask you if you want Visual Studio to update all references to that form. Click Yes, and you’re done.

answered Aug 7, 2011 at 2:30

Only Bolivian Here's user avatar

You can use Form.Text property to get/set the title of the form either in design time or at runtime depending upon your requirement.
If you want to have a dynamic title that changes based on some events you can set it during the runtime for e.g. if you are showing the progress of a task in your form you will want to put the percentage completed in the title.

answered Aug 7, 2011 at 2:33

Gaurav's user avatar

GauravGaurav

8404 silver badges16 bronze badges

answered Aug 7, 2011 at 2:22

hivie7510's user avatar

hivie7510hivie7510

1,24610 silver badges23 bronze badges

1

  • Not sure what happened with the first pasting, but it is fine now. Thanks

    Aug 7, 2011 at 2:34

I believe you can just change the filename of the form to the one you want in design time.

answered Aug 7, 2011 at 2:27

SoftwareGeek's user avatar

SoftwareGeekSoftwareGeek

15.3k19 gold badges62 silver badges78 bronze badges

2

  • You should not do it that way unless you have a trival name such as Form1. If you require a title such as «User Entry Form», then making that the file name would be a bad idea.

    Aug 7, 2011 at 2:35

  • @hivie7510 — agree, it was a simple question that skipped my attention.

    Aug 7, 2011 at 20:51

  • The Overflow Blog
  • Featured on Meta

Related

Hot Network Questions

  • What should one do to help Israel during war?

  • How to know the sample arithmetic mean and standard deviation if I know the mean and the deviation of the logarithm of the observations

  • Contradiction in negative mass interactions according to GR

  • How do Landau and Lifshitz avoid the ergodicity problem?

  • How can I write the equation of the parabola passing through list of three points?

  • How to exclude some files and folder in telescope?

  • In the Spanish-American War (1898), who formally declared war first?

  • How to stop Steam trying to read from a non-existent drive?

  • Why does causality imply that the system function is analytic?

  • Is the Clebsch-Gordan decomposition of Lie algebra or Lie group representations?

  • Copy contents of one file to another using sed

  • How to force the misalignment of subscript and superscript

  • Redefining queue with different front and rear

  • Copying files to directories according the file name

  • How to identify transcendental numbers?

  • Difference between KDE, MLE and EM for density estimation

  • Beacon contract contructor seems to call address 0x02?

  • What do to with this vent?

  • A Trivial Pursuit #18 (Sports and Leisure 3/4): Connected

  • What makes some players so good?

  • Why did Doctor Strange believe the Fantastic Four were related to popular music in the 1960s?

  • Why do Atlas III and V use Russian RD-180 engines?

  • Why do some Chinese shows avoid using real toponyms?

  • How would a Bayesian define a fair coin?

more hot questions

Question feed

Your privacy

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

How do I rename the name of already created Windows Form? Currently, its default name is Form1 and when the application runs its name is shown in the top-left side of window.
How do I rename this text to MyForm?

Refactoring changes the name of the .cs files, but the text in window does not change.
Moreover, I tried to change default icon of the form by using Project->Properties->Browse to the location of the .ico file, but the default icon didn’t change. Why doesn’t that work?

  • c#
  • winforms
  • icons
  • rename

Sameer Singh's user avatar

Sameer Singh

1,3581 gold badge19 silver badges47 bronze badges

asked Aug 1, 2013 at 9:42

Nurlan's user avatar

NurlanNurlan

2,87019 gold badges47 silver badges65 bronze badges

2

  • The Properties -> Project Icon property is used to change the executable’s icon and not the icon displayed by the Form. See the Form’s Icon property to change the Form’s Icon.

    Aug 1, 2013 at 9:49

  • The default Name of your form is also the same to the default Text of your form.

    Aug 1, 2013 at 10:08

3 Answers

You would need to change the Form’s Text property;

This can be done VIA the properties or within code;

enter image description here

Or (from the constructor)

this.Text = "MyForm";

Hope this helps?

answered Aug 1, 2013 at 9:48

Hexie's user avatar

HexieHexie

3,9856 gold badges32 silver badges55 bronze badges

8

  • There is no Text property in Properties of Form. Instread there are properties such as Name of file, Full Path, Action when building, etc..

    Aug 1, 2013 at 9:54

  • @NurlanKenzhebekov Then I think you’re looking in the wrong place, have you tried (from your Form1’s constructor) to change it VIA code? (i.e. this.Text = "MyForm";)

    Aug 1, 2013 at 9:56

  • @NurlanKenzhebekov you are mixed up with properties of Form.cs (File propeties).

    Aug 1, 2013 at 9:57

  • @Hexie the OP also wants to rename his Form, you miss that.

    Aug 1, 2013 at 9:58

  • No he doesn’t. He wants to change the text displayed in the title bar. That’s set by the Text property. All objects that inherit from System.Windows.Forms.Control have it. This answer is correct as it stands.

    Aug 1, 2013 at 9:59

Change the Text property of the Form in designer mode.

answered Aug 1, 2013 at 9:46

Moo-Juice's user avatar

Moo-JuiceMoo-Juice

38.3k10 gold badges78 silver badges129 bronze badges

Change the Text property of the Form in designer mode.

answered Aug 1, 2013 at 11:51

Deadlock's user avatar

DeadlockDeadlock

3301 gold badge3 silver badges21 bronze badges

0 / 0 / 1

Регистрация: 25.08.2014

Сообщений: 57

1

Изменить заголовок формы

15.05.2015, 18:29. Показов 14800. Ответов 19


Студворк — интернет-сервис помощи студентам

Помогите пожалуйста мне надо что бы при нажатии на кнопку в с# переименовывалась названия формы?
помогите пожалуйста…..



0



Programming

Эксперт

94731 / 64177 / 26122

Регистрация: 12.04.2006

Сообщений: 116,782

15.05.2015, 18:29

19

Tsin

746 / 487 / 187

Регистрация: 30.12.2012

Сообщений: 1,278

Записей в блоге: 2

15.05.2015, 18:39

2

bilolbek, в обработчик события нажатия кнопки добавьте

C#
1
form1.Text = "New title"; //Где form1 - имя формы



0



0 / 0 / 1

Регистрация: 25.08.2014

Сообщений: 57

18.05.2015, 17:20

 [ТС]

3

извините за глупый вопрос но где это обработчик события



0



746 / 487 / 187

Регистрация: 30.12.2012

Сообщений: 1,278

Записей в блоге: 2

18.05.2015, 17:25

4

bilolbek, если вы его не создали, то нужно сделать это. Можно через дизайнер. Двойной клик по кнопке на форме автоматически создаст в коде формы обработчик для Click



0



bilolbek

0 / 0 / 1

Регистрация: 25.08.2014

Сообщений: 57

18.05.2015, 17:28

 [ТС]

5

Цитата
Сообщение от Tsin
Посмотреть сообщение

bilolbek, если вы его не создали, то нужно сделать это. Можно через дизайнер. Двойной клик по кнопке на форме автоматически создаст в коде формы обработчик для Click

но выдает ошибку:Ошибка Для нестатического поля, метода или свойства «System.Windows.Forms.Control.Text.get» требуется ссылка на объект \Form1.cs
я там написал

C#
1
    Form1.Text = "next";



0



Ev_Hyper

Заблокирован

18.05.2015, 17:30

6

bilolbek,

C#
1
this.Text = "next";



0



Tsin

746 / 487 / 187

Регистрация: 30.12.2012

Сообщений: 1,278

Записей в блоге: 2

18.05.2015, 17:30

7

bilolbek, потому что Form1 — это не объект, а класс. В вашем случае сработает

C#
1
this.Text = "next";



0



bilolbek

0 / 0 / 1

Регистрация: 25.08.2014

Сообщений: 57

18.05.2015, 17:44

 [ТС]

8

C#
1
2
3
4
        private void button1_Click(object sender, EventArgs e)
        {
 
        }

name формы :Form1
название(где text) я написал допустим «привет»
и при нажатии на кнопку мне надо чтобы названия формы переименовалась на «пока»



0



Ev_Hyper

Заблокирован

18.05.2015, 17:53

9

Лучший ответ Сообщение было отмечено bilolbek как решение

Решение

Цитата
Сообщение от bilolbek
Посмотреть сообщение

и при нажатии на кнопку мне надо чтобы названия формы переименовалась на «пока»

bilolbek,

C#
1
2
3
4
        void button1_Click(object sender, EventArgs e)
        {
            this.Text = "Пока";  
        }



1



4 / 3 / 1

Регистрация: 24.09.2016

Сообщений: 320

03.02.2022, 11:53

10

. .. а как потом пользователю можно изменить название на другое ? . . . ведь новое название не сохраняется при новом открытии формы ? . . . потому что в Дизайнере формы — будет старое название . . что — при каждом открытии формы менять название ?



0



2743 / 1654 / 877

Регистрация: 14.04.2015

Сообщений: 5,637

03.02.2022, 12:00

11

DLD, используйте properties, как вариант, для хранения переменной заголовка формы. меняйте ее, когда вздумается, и при запуске используйте название оттуда же



2



ViterAlex

8934 / 4846 / 1886

Регистрация: 11.02.2013

Сообщений: 10,246

03.02.2022, 12:10

12

DLD, использовать класс Settings, чтобы хранить значения между запусками приложения. См. скриншоты.
И затем добавить сохранение настроек в событие ApplicationExit.

C#
1
2
3
4
5
6
7
8
9
10
11
12
static void Main()
{
    Application.EnableVisualStyles();
    Application.ApplicationExit += Application_ApplicationExit;
    Application.SetCompatibleTextRenderingDefault(false);
    Application.Run(new Form1());
}
 
private static void Application_ApplicationExit(object sender, EventArgs e)
{
    Properties.Settings.Default.Save();
}

Настройки хранятся в %LOCALAPPDATA%\<Имя проекта>

Миниатюры

Изменить заголовок формы
 

Изменить заголовок формы
 



2



4 / 3 / 1

Регистрация: 24.09.2016

Сообщений: 320

03.02.2022, 15:29

13

ViterAlex, спасибо большое за подробный ответ



0



4 / 3 / 1

Регистрация: 24.09.2016

Сообщений: 320

04.02.2022, 00:33

14

ViterAlex, примерно так и сделал. Только новое название формы для удобства — предоставил пользователю возможность устанавливать не в Settings, а в диалоговом окне новой формы



0



2743 / 1654 / 877

Регистрация: 14.04.2015

Сообщений: 5,637

04.02.2022, 09:05

15

DLD, в settings хранится название, и пример был предоставлен для Вас, чтобы Вы сделали это первый раз. Само собой пользователь никак не может это сделать через exe, так как это возможности visual studio. Что-то Вы написали не подумав.



0



4 / 3 / 1

Регистрация: 24.09.2016

Сообщений: 320

04.02.2022, 16:13

16

AndreyVorobey, вот цитата из моего самого первого поста . .. цитирую — » .. а как потом пользователю можно изменить название на другое ? » . . .. Это подтверждает что меня интересовало именно — чтобы пользователь менял название как ему хочется. . . .
. . Просто интересно — другой вопрос . . . может скажете заодно — под названием папки «%LOCALAPPDATA%» — имелась ввиду папка «C:\Users\[имя пользователя]\AppData\Local» ?



0



2743 / 1654 / 877

Регистрация: 14.04.2015

Сообщений: 5,637

04.02.2022, 16:16

17

DLD, для чего Вам эта папка? Может, это все таки путь к exe? Я не особо улавливаю суть вопроса



0



4 / 3 / 1

Регистрация: 24.09.2016

Сообщений: 320

04.02.2022, 18:28

18

для чего нужна ? . .. теперь уже не нужна . . однако — я же написал — просто интересно . . . А почему именно эта папка — почитайте выше рекомендацию . . мне ее рекомендовали . . а суть вопроса простая — речь идет об одной и той же папке или это разные папки ? . ..напоминаю название — ( «%LOCALAPPDATA%» — и «C:\Users\[имя пользователя]\AppData\Local»)



0



2743 / 1654 / 877

Регистрация: 14.04.2015

Сообщений: 5,637

04.02.2022, 18:42

19

DLD, увидел, где писали

Настройки хранятся в %LOCALAPPDATA%\<Имя проекта>

ну так что Вам не понятно? это полный путь, где находится проект, причем тут AppData\Local? если у Вас по этому пути находятся все создаваемые из-под VS проекты, то это одна и та же папка, если нет, то разные.
а добавленные значения хранятся в файле проекта App.config



0



8934 / 4846 / 1886

Регистрация: 11.02.2013

Сообщений: 10,246

04.02.2022, 18:55

20

Цитата
Сообщение от DLD
Посмотреть сообщение

может скажете заодно — под названием папки «%LOCALAPPDATA%» — имелась ввиду папка «C:\Users\[имя пользователя]\AppData\Local»

Смотрите переменные окружения в Windows. Команда set в консоли.

Добавлено через 3 минуты

Цитата
Сообщение от AndreyVorobey
Посмотреть сообщение

добавленные значения хранятся в файле проекта App.config

AndreyVorobey, только если для свойства выставлен scope = Application. По умолчанию и у меня на скриншоте, свойства создаются в контексте User. Специально об этом не говорил, чтобы не запутывать.

Цитата
Сообщение от AndreyVorobey
Посмотреть сообщение

причем тут AppData\Local?

Потому что пользовательские настройки хранятся в %LOCALAPPDATA%\<Имя проекта>. Изменить это нельзя, но можно управлять версиями настроек внутри этой папки.



1



  • Как перейти в нужную папку в командной строке windows 10
  • Как перейти в службы windows 10
  • Как переименовать юзер на windows 10
  • Как перейти в корзину windows
  • Как переименовать этот компьютер в мой компьютер windows 10