Button does not contain a definiton for ID

471 views Asked by At

This is my Form1.cs file. The method should display by a MessageBox the clicked button's ID, but I get this error.

private void button_Click(object sender, EventArgs e)
        {

            Button button = sender as Button;
            string buttonId = button.ID;
            MessageBox.Show(buttonId);
        }

Error:

'Button' does not contain a definition for 'ID' and no extension method 'ID' accepting a first argument of type 'Button' could be found (are you missing a using directive or an assembly reference?)

1

There are 1 answers

7
Lars Kristensen On

If this is a Windows Forms application, then the built in Button controls do not have a property called ID. You probably want to fetch the Name property, which is unique for each button control.

A quick example:

private void button_Click(object sender, EventArgs e)
{
    Button button = sender as Button;
    string buttonName = button.Name; //Button does not have an ID - use Name instead
    MessageBox.Show(buttonName);
}