Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Move a button's location after it is already drawn

Tags:

c#

winforms

On my C# Winform (VS 2010 / C# / .Net 3.5), I have created a button in the designer. I want to move and resize that button to a different location based on a user's setting upon start-up of that form.

In my form's load event, I have the following code to move and resize the button:

btnShare.Location = new System.Drawing.Point(16, 496);
btnShare.Margin = new System.Windows.Forms.Padding(4);
btnShare.Size = new System.Drawing.Size(408, 126);

All of the code to create the button is *.designer.cs file for this particular form.

The problem is this: When the form loads, I can see the button in it's new location based on the 3 lines of code above. But then when the form is done loading and going through all it's events, the button goes back to it's original location which is in the *.designer.cs InitalizeComponent() method.

I do not want to take the code out of the *.designer.cs file and put it only into the form's .cs file because I still want to be able to see the button in the designer when I work on the design of the form.

I just want to move and resize the button if the user has that option toggled upon loading of the form.

How can I do this since .Net seems to draw the buttons on my form after the load event has processed thus moving the button back to it's original spot?

like image 413
fraXis Avatar asked Jun 26 '12 18:06

fraXis


1 Answers

Here's some code I just spiked together. and It works for me.

This is a SSCCE, a Simple, Self-Contained Correct Example. Very useful when asking questions on SO.

*Since I don't know what your specific problem is, the Correct, part might not be accurate in this case

Try and make a copy of this project, and see if you experience the same issue. If you don't than We really can't help you that much without getting more information about your project.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();

            button1.Location = new Point(40, 40);
        }
    }
}
like image 115
Sam I am says Reinstate Monica Avatar answered Oct 29 '22 01:10

Sam I am says Reinstate Monica