Question

I'm fairly new to C# (and programming in general) so stick with me if I make any huge errors or talk complete bull. So what I'm trying to do is have a private void that resizes the background image of a button. I send the name of the button to the private void via a string. Anyway, the code looks something like this:

ButtonResize("Zwaard");


protected void ButtonResize(string Button)
    {
        string ButNaam = "btn" + Button;
        Button Butnaam = new Button();
        Butnaam.Text = ButNaam;

        if (Butnaam.BackgroundImage == null)
        {
            return;
        }
        else
        {
            var bm = new Bitmap(Butnaam.BackgroundImage, new Size(Butnaam.Width, Butnaam.Height));
            Butnaam.BackgroundImage = bm;
        }
     }

But it doesn't work like that. I can't seem to find a way to declare a new object named the value I have in a string. What I want my code to do is instead of making a button called "Butnaam", I want it to create a button called btnZwaard (the value of the string Butnaam).

How do I tell C# I want the value of the variable to be the name of a new button, not literally what I type?

Thanks in advance.

Was it helpful?

Solution

Are you looking for something like this? By passing the Button to the method you can then act on the object. If this is what you are looking for then you should read Passing Reference-Type Parameters

protected void ButtonResize(Button button)
    {
        if (button != null && button.BackgroundImage != null)
        {
            button.BackgroundImage = new Bitmap(button.BackgroundImage, new Size(newWidth, newHeight));
        }
     }

OTHER TIPS

A string is a piece of text. You subsequently refer to it as a class, which is wrong. Assuming it were right you create a new button rather than "resize its image".

What you want to do to get you started is create a new function in the same class as the dialog that has the button. That function can resize the image of the control.

Edit: this doesn't seem like a good starting point for learning a language, btw. Please find a good online tutorial for starting in C# (e.g. a hello world application).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top