0

So I'm trying to figure out how to change a buttons text based on having the buttons name as a variable. I already know how to change a buttons text by hardcoding its name like Button1.Text = "hello";

But I want to be able to do something like storing Button1's name in a string called value and then use that string to modify the buttons text so i can use a method for several buttons instead of pasting a huge similar block of code in every buttons method, I just cant seem to figure out how. Any ideas would help.

private void Button3_Click(object sender, EventArgs e)
        {
            Button obj = sender as Button;
            string buttonname = obj.Name;
            boxfill(buttonname);
        }
private void Button4_Click(object sender, EventArgs e)
        {
            Button obj = sender as Button;
            string buttonname = obj.Name;
            boxfill(buttonname);
        }
private void Button5_Click(object sender, EventArgs e)
        {
            Button obj = sender as Button;
            string buttonname = obj.Name;
            boxfill(buttonname);
        }
// this will send the buttons name to boxfill

private void boxfill(string value)
        {
            // will ideally change the button named with value's
            // text to "x"
        }
ProgrammingLlama
  • 36,677
  • 7
  • 67
  • 86
  • Why do you need the name as a string at all? Why not just pass the button itself to `boxfill()`? – Ken White Apr 16 '19 at 02:01
  • You have to realise the truth: there is no Visual Studio button, it is only a UI library button. Remember that Visual Studio is an IDE, it does not provide the libraries of the .NET Framework, nor does it run your code. It even passes the job of building your code to a different EXE. -- Now we've got that out of the way, are you using WinForms? – ProgrammingLlama Apr 16 '19 at 02:01
  • 1
    Yes, I'm using WinForms – Conor Mcquillan Apr 16 '19 at 02:04
  • Perhaps [this will help you](https://stackoverflow.com/a/40206006/3181933)? Although accessing buttons dynamically by textual name seems a bit strange to me, unless you're building a dynamically generated UI. – ProgrammingLlama Apr 16 '19 at 02:05
  • 2
    Possible duplicate of [Get a Windows Forms control by name in C#](https://stackoverflow.com/questions/1536739/get-a-windows-forms-control-by-name-in-c-sharp) – Ken White Apr 16 '19 at 02:07
  • Thanks John and Ken, solved my problem by just passing the button itself, didn't know that was an option. – Conor Mcquillan Apr 16 '19 at 02:24
  • Thanks Ken and John, that solved my problem. – ArduinoBen Dec 16 '20 at 04:23

0 Answers0