S
S
Sergey Khlopov2017-10-03 15:02:39
Programming
Sergey Khlopov, 2017-10-03 15:02:39

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#)?
59d37aae58869809048826.jpeg
Briefly introduced into the program structure, there are 3 objects:

NewClassProgram NewObject1 = new NewClassProgram();
NewClassProgram2 NewObject2 = new NewClassProgram2();
NewClassProgram3 NewObject3 = new NewClassProgram3();

By clicking on each button (button1,button2,button3), the corresponding object enters the PropertyGrid (more precisely, its fields)
private void button1_Click(object sender, EventArgs e)
        {
            GridObject.SelectedObject = NewObject1;
        }

Now I have made Drag-and-drop functions, now these buttons can be dragged to another area (B). And now the question arose in how to make it so that the button would remain in place in the area (A), and its copy would fall into another area, that is, into the area (B).
Thank you very much in advance for your reply.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
P
Peter, 2017-10-03
@petermzg

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.

D
Dmitry Bashinsky, 2017-10-03
@BashkaMen

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;

There may be errors in the code, since I haven’t written on forms for a long time, and this code is written right here, and not in the studio with Intelisence :)
I hope it helps

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question