Question

This is a bit of a noob question, but I'm trying to use a string (myButton), which is set according to the button that called the method, and trying to use that string inside an argument, but my IDE thinks I'm using the string directly. Here's the code:

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 GMA
{
     public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
            string myButton;//Currently selected button

            private void button1_Click(object sender, EventArgs e)//This will be replicated for every button on the Form
            {
                myButton = "button1";
                SoundRoute();
            }

            public void SoundRoute()
            {
                if ((myButton).Text == string.Empty)//This is the line I'm having trouble with. I want the string of myButton to be converted to button1, button2, etc.
                {
                SoundCall subForm = new SoundCall();
                subForm.Show();
                }
            }
    }
}

I'd appreciate any help. I know I could just make a new one for each button, but this is as much for learning purposes as for practical. I've looked all over for the answer but no luck.

Was it helpful?

Solution

Use the sender argument and pass it to your SoundRoute method.. that is actually what its for:

public void SoundRoute(object sender)
{
    if (((Button)sender).Text == string.Empty)//This is the line I'm having trouble with. I want the string of myButton to be converted to button1, button2, etc.
    {
        SoundCall subForm = new SoundCall();
        subForm.Show();
    }
}

Then your events become:

 private void button1_Click(object sender, EventArgs e)//This will be replicated for every button on the Form
 {
     SoundRoute(sender);
 }

Then, you can have a single event that all buttons are wired up to (since it "will be replicated for all buttons on the form").

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