Improve Article
Save Article
Improve Article
Save Article
A Button is an essential part of an application, or software, or webpage. It allows the user to interact with the application or software. In Button, you are allowed to set the name of your button by using Name property. You can use this property in two different methods:
1. Design-Time: It is the easiest method to set the name of the button 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 Button control from the ToolBox and drop it on the windows form. You are allowed to place a Button control anywhere on the windows form according to your need.
- Step 3: After drag and drop you will go to the properties of the Button control to set the Name property of the Button.
Output:
Run-Time: It is a little bit trickier than the above method. In this method, you can set the Name property of the Button programmatically with the help of given syntax:
public string Name { get; set; }
Here, the string is used to represent the name of the button. Following steps are used to set the Name property of the Button:
- Step 1: Create a button using the Button() constructor is provided by the Button class.
// Creating Button using Button class Button MyButton = new Button();
- Step 2: After creating Button, set the Name property of the Button provided by the Button class.
// Set the name of the button Mybutton.Name = "First_button";
- Step 3: And last add this button control to form using Add() method.
// Add this Button to form this.Controls.Add(Mybutton);
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
WindowsFormsApp8 {
public
partial
class
Form1 : Form {
public
Form1()
{
InitializeComponent();
}
private
void
Form1_Load(
object
sender, EventArgs e)
{
Label l =
new
Label();
l.AutoSize =
true
;
l.Text =
"Do you want to submit this form?"
;
l.Location =
new
Point(222, 145);
this
.Controls.Add(l);
Button Mybutton =
new
Button();
Mybutton.Location =
new
Point(225, 198);
Mybutton.Text =
"Submit"
;
Mybutton.AutoSize =
true
;
Mybutton.BackColor = Color.LightBlue;
Mybutton.Padding =
new
Padding(6);
Mybutton.Name =
"First_button"
;
this
.Controls.Add(Mybutton);
Button Mybutton1 =
new
Button();
Mybutton1.Location =
new
Point(438, 198);
Mybutton1.Text =
"Cancel"
;
Mybutton1.AutoSize =
true
;
Mybutton1.BackColor = Color.LightPink;
Mybutton1.Padding =
new
Padding(6);
Mybutton1.Name =
"Second_button"
;
this
.Controls.Add(Mybutton1);
}
}
}
Output:
Improve Article
Save Article
Improve Article
Save Article
A Button is an essential part of an application, or software, or webpage. It allows the user to interact with the application or software. In Button, you are allowed to set the name of your button by using Name property. You can use this property in two different methods:
1. Design-Time: It is the easiest method to set the name of the button 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 Button control from the ToolBox and drop it on the windows form. You are allowed to place a Button control anywhere on the windows form according to your need.
- Step 3: After drag and drop you will go to the properties of the Button control to set the Name property of the Button.
Output:
Run-Time: It is a little bit trickier than the above method. In this method, you can set the Name property of the Button programmatically with the help of given syntax:
public string Name { get; set; }
Here, the string is used to represent the name of the button. Following steps are used to set the Name property of the Button:
- Step 1: Create a button using the Button() constructor is provided by the Button class.
// Creating Button using Button class Button MyButton = new Button();
- Step 2: After creating Button, set the Name property of the Button provided by the Button class.
// Set the name of the button Mybutton.Name = "First_button";
- Step 3: And last add this button control to form using Add() method.
// Add this Button to form this.Controls.Add(Mybutton);
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
WindowsFormsApp8 {
public
partial
class
Form1 : Form {
public
Form1()
{
InitializeComponent();
}
private
void
Form1_Load(
object
sender, EventArgs e)
{
Label l =
new
Label();
l.AutoSize =
true
;
l.Text =
"Do you want to submit this form?"
;
l.Location =
new
Point(222, 145);
this
.Controls.Add(l);
Button Mybutton =
new
Button();
Mybutton.Location =
new
Point(225, 198);
Mybutton.Text =
"Submit"
;
Mybutton.AutoSize =
true
;
Mybutton.BackColor = Color.LightBlue;
Mybutton.Padding =
new
Padding(6);
Mybutton.Name =
"First_button"
;
this
.Controls.Add(Mybutton);
Button Mybutton1 =
new
Button();
Mybutton1.Location =
new
Point(438, 198);
Mybutton1.Text =
"Cancel"
;
Mybutton1.AutoSize =
true
;
Mybutton1.BackColor = Color.LightPink;
Mybutton1.Padding =
new
Padding(6);
Mybutton1.Name =
"Second_button"
;
this
.Controls.Add(Mybutton1);
}
}
}
Output:
Forni 0 / 0 / 0 Регистрация: 28.04.2015 Сообщений: 18 |
||||||||
1 |
||||||||
Как переименовать кнопку09.05.2015, 09:51. Показов 8566. Ответов 8 Метки нет (Все метки)
Есть два кода, тут особо ничего не происходит:
А тут я пытаюсь переименовать одну из кнопок:
Т.е. вся разница в «button1.Text = Convert.ToString(pyat[1]);», но в первом случае программа запускается, а во втром вылетает, подскажете, в чем проблема?
__________________
0 |
Serx 63 / 69 / 22 Регистрация: 28.04.2015 Сообщений: 194 Записей в блоге: 1 |
||||
09.05.2015, 10:11 |
2 |
|||
Добавлено через 5 минут
1 |
0 / 0 / 0 Регистрация: 28.04.2015 Сообщений: 18 |
|
09.05.2015, 10:12 [ТС] |
3 |
Нет-нет, это понятно. Мне нужно расставлять значения текста на кнопках при начале программы. До любых нажатий. А еще можно поставить InitializeComponent(); перед «button1.Text = Convert.ToString(pyat[1]);», поскольку поле InitializeComponent(); загружает компоненты формы, такие как кнопка А вот это помогло, затупил я, спасибки)
0 |
Serx 63 / 69 / 22 Регистрация: 28.04.2015 Сообщений: 194 Записей в блоге: 1 |
||||
09.05.2015, 10:14 |
4 |
|||
InitializeComponent(); ставь в самое начало конструктора Form1()
0 |
6187 / 2439 / 717 Регистрация: 11.04.2015 Сообщений: 3,948 Записей в блоге: 43 |
|
09.05.2015, 10:14 |
5 |
Forni, ты обращаешься к кнопке до её создания. Попробуй обратиться к ней после вызова InitializeComponent
0 |
lokilo 115 / 116 / 52 Регистрация: 19.12.2014 Сообщений: 612 |
||||
09.05.2015, 10:21 |
6 |
|||
Forni, я даже и не знаю где вы находите такие коды, и кто так вообще делает? помещать в конструктор формы простое переименование кнопки
0 |
63 / 69 / 22 Регистрация: 28.04.2015 Сообщений: 194 Записей в блоге: 1 |
|
09.05.2015, 10:24 |
7 |
я даже и не знаю где вы находите такие коды, и кто так вообще делает? помещать в конструктор формы простое переименование кнопки Помню я так же делал, когда начинал изучение программирования
0 |
0 / 0 / 0 Регистрация: 28.04.2015 Сообщений: 18 |
|
09.05.2015, 10:28 [ТС] |
8 |
Верно, верно. Это все полностью моя писанина. Больше ошибаюсь, быстрей вникаю. Видимо, пока только так.)
0 |
63 / 69 / 22 Регистрация: 28.04.2015 Сообщений: 194 Записей в блоге: 1 |
|
09.05.2015, 10:35 |
9 |
Лучше, поскольку удобней и читабельней запихнуть код в метод и написать одной стройкой в конструктор формы имя метода Добавлено через 6 минут
0 |
I am starting with C# programming, I have a scenario, where I create a windows form application. I have created a button inside the form and double click it to generate its associated click function. The visual studio generates the function with default name.
private void button1_Click(object sender, EventArgs e)
{
}
Now when I rename the button in properties, the function name remains same, making it difficult to relate button and function, I have an old code where a lot of such cases are present. So, I cannot delete and recreate the buttons and other things.
How can I rename the functions when I rename the button?
asked Jul 12, 2017 at 11:52
2
Right click on the function name and select Rename. The name will be highlighted (it’s green on my system, see picture below). Edit the name and then hit the Apply button. The button’s click event will correctly point to the newly renamed method.
answered Jul 12, 2017 at 14:22
Idle_MindIdle_Mind
37.5k3 gold badges28 silver badges39 bronze badges
You can change the name of the method by simply typing the new name in place of the old one when editing the code. Just like changing any text.
Then you can validate that the control still uses that event by either:
- Go to the Form designer and select the control. Check its properties/events and make sure the name still lines up.
- Go to the code generated by the form designer and find where it assigns the method to the event, and change it if it needs to be changed.
Either one of these should also update the other one automatically, though I imagine it’s generally preferred to use the first approach for consistency with the rest of the form design process.
Note that the method name can be anything you like, there’s no steadfast rule that says it must be controlName_eventName(object sender, EvenArgs e)
. For example, if you have multiple controls which share an event handler then you don’t have to decide which control gets to be the one in the method name. You can give it any common name, such as saveFormChanges(object sender, EvenArgs e)
and still assign it as the handler for that event.
answered Jul 12, 2017 at 11:57
DavidDavid
201k35 gold badges195 silver badges271 bronze badges
You need to change the name of Event from the property window.
answered Jul 12, 2017 at 11:54
Yogesh PatelYogesh Patel
8182 gold badges12 silver badges26 bronze badges
go to your designer Right Click -> Properties (F4) -> Events -> ClickEvent -> Type in the name what so ever you want and click this will create Click event with the name you entered
answered Jul 12, 2017 at 11:57
Vicky SVicky S
7624 silver badges16 bronze badges
change button1_Click
method name in code to new name and then press ctrl+. (period) and chose Rename. Alternatively, click on light bulb and select Rename.
answered Jul 12, 2017 at 11:57
NinoNino
6,8112 gold badges26 silver badges42 bronze badges
Name of the function does not necessary need to match button name, it’s just the convention which makes it easier to understand which element is bound to which function on which event.
If you enter the FormName.Designer.cs
file, you will find InitializeComponent
function which contains the properties setup of all form elements, including their event binding. For example, you will probably have something like this over there:
this.button1.Click += new System.EventHandler(this.button1_Click);
where button1
is name of the element, Click
is name of the event of that element and button1_Click
is the name of the function handling that event.
If you’re in the design mode of the form FormName.cs [Design]
you can find the lightning icon inside the VisualStudio Properties
window (one of the tabs next to your Solution Explorer
tab). Under that icon, you will find the list of all the possible events of the currently selected element in your designer. On the example of your button it should look like this:
You can handle the event binding either here or inside your FormName.Designer.cs
file, but it’s preferable through this view because content of the Designer
file is automatically generated. InitializeComponent
function is then called inside the constructor of your form which initializes the form based on the setup of your designer file.
answered Jul 12, 2017 at 12:05
msmolcicmsmolcic
6,3297 gold badges31 silver badges56 bronze badges