views:

68

answers:

6

I designed a button

How do I inherit the rest of this button?

button

+3  A: 

I'm assumimg what you want is: defining 10 buttons, and styling(set several properties of) button1, you want the rest 9 buttons the same as button1. This is not inheritance in C#. To meet your requirement, you can get those 10 buttons into one list/collection/array/etc...one way to get the buttons probably looks like:

var buttons = container.Controls.OfType<Button>();

And then loop the list to set properties:

foreach(var button in buttons)
{
   //set the common properties.
}
Danny Chen
+3  A: 

You can create a new class, subclass the standard Button, and make your style adjustments in the constructor. Once that's done, rebuild your project, and your new component should appear in the Toolbox in the top section. Use it instead of the standard Button and you should be good to go.

public class MyButton : Button
{
    public MyButton() : base()
    {
        // set whatever styling properties needed here
        ForeColor = Color.Red;
    }
}
Anna Lear
This act is called inheritance?
ehsan_d18
Yes, but are you sure you want to derive a class simply to change the ForeColor?
wj32
no ، I want a lot of work to do
ehsan_d18
@wj32 Well, this was sample code. Normally, no, but the OP's example showed a heavily styled button where more properties would need to be changed.
Anna Lear
@ehsan_d18 This is inheritance in the sense that you're subclassing the original Button class. So 'MyButton' inherits from 'Button'.
Anna Lear
+1  A: 

Does this method of inheritance is true?

mycode :

    public class MyButton : Button
{

    public MyButton()
        : base()
    {
        // set whatever styling properties needed here
        this.ForeColor = Color.Blue;
        this.Click += new EventHandler(MyButton_Click);
        this.BackColor = Color.Red;
    }

    void MyButton_Click(object sender, EventArgs e)
    {
        MessageBox.Show("yes");
    }
}

Why not change the background color?

background color

ehsan_d18
A: 

Why not run this code?

this.BackColor = Color.Red;
ehsan_d18
A: 

Normally, i create a child class of the button and then drag the new button from the toolbox to the win form.

lauhw
A: 

All properties are subject to change

Except the background color

Is this a normal thing

No solution?

ehsan_d18