Use a variable to change a button size

Hi Experts,

using C# I have got a string  from a database (75, 75), I now want to assign this string so it will become the new size of various buttons I have on my form,  something like:

string  myButtonSize;
button1.Size = new System.Drawing.Size(myButtonSize)

Hope somebody can help
dizzycatAsked:
Who is Participating?
 
Robert SchuttSoftware EngineerCommented:
There's no direct method Size.FromString but you can use the TypeConverter Class like this:
try {
    string myButtonSize = textBox1.Text;
    button1.Size = (System.Drawing.Size)TypeDescriptor.GetConverter(typeof(System.Drawing.Size)).ConvertFromString(myButtonSize);
}
catch (Exception ex) {
    MessageBox.Show(ex.ToString(), ex.Message);
}

Open in new window

capture
0
 
Robert SchuttSoftware EngineerCommented:
Alternatively, you can define your own Size.FromString() method using extension methods:
namespace EE_Q_28644875 {
    public partial class Form1 : Form {
        public Form1() {
            InitializeComponent();
        }

        private void textBox1_TextChanged(object sender, EventArgs e) {
            try {
                string myButtonSize = textBox1.Text;
                button1.Size = Size.FromString(myButtonSize);
            }
            catch (Exception ex) {
                MessageBox.Show(ex.ToString(), ex.Message);
            }
        }
    }

    public static class ExtensionsClass {
        public static System.Drawing.Size FromString(this System.Drawing.Size sz, string s) {
            try {
                string[] arr = s.Split(new char[] { ',', ' ' }, StringSplitOptions.RemoveEmptyEntries);
                System.Drawing.Size newsz = new System.Drawing.Size(Convert.ToInt32(arr[0]), Convert.ToInt32(arr[1]));
                return newsz;
            }
            catch (Exception ex) {
                return new System.Drawing.Size(1, 1); // think of a more useful default or throw error
            }
        }
    }
}

Open in new window

0
 
dizzycatAuthor Commented:
Thanks Robert, this works just great.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.