Answer the question
In order to leave comments, you need to log in
How to create a copy of a button in C#?
Hello, please tell me how to create a copy of a button in WindowsForm (C#)?
Briefly introduced into the program structure, there are 3 objects:
NewClassProgram NewObject1 = new NewClassProgram();
NewClassProgram2 NewObject2 = new NewClassProgram2();
NewClassProgram3 NewObject3 = new NewClassProgram3();
private void button1_Click(object sender, EventArgs e)
{
GridObject.SelectedObject = NewObject1;
}
Answer the question
In order to leave comments, you need to log in
When you place buttons on a form in the designer, the studio places the creation code in the
InitializeComponent method.
See how the creation is done there, the binding of events and the indication of the parent, and by analogy, do it in your code.
When you start dragging, remember the coordinates of the button, if you dragged it to B, then make a copy and put it in the previous place.
Since the button is a class and not a structure, we cannot simply copy the A = B method; because the type is a reference class and all that the current operation will do is create another reference to the same object. It is necessary to transfer the values to a new object, something like this:
var copyBtn = new Button
{
// А тут перенести нужные свойства.
Location = myBtn.Location,
Text = myBtn.Text,
};
// И наверное тоже главное что б кнопка делала тоже самое что и та которую копируем.
copyBtn.Click += //тут просто название метода на которую подписана кнопка, если метод в этом контексте. (myBtn_OnClick).
// В завершении мы должны добавить кнопку на ту панель (B) припустим у нее имя panel1
panel1.Controls.Add(copyBtn);
// Ну а тут верни кнопку обратно.
myBtn.Location = SaveLocation;
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question