简体   繁体   中英

C# - Add custom property/attribute to new button

I try to developp an app for users to create a lot of computer's configuration, with OS / Language / etc ...

When he validate a configuration, I would like the choices to be stored in a custom attribute button

    private void VALIDATE_Click(object sender, EventArgs e)
            { 

                string Computer = Text_Computer.Text;
                if (myList.Any(str => str.Contains(Computer)))
                {
                    MessageBox.Show(Computer+"Already Exist");
                }
                else
                {
                    Button button = new Button();
                    button.Size = new System.Drawing.Size(195, 30);
                    button.Tag = Computer;
                    button.Name = Computer;
                    button.Text = Computer;
                    button.CustomOS = comboBox_OS.SelectedItem;
                    button.CustomLanguage = comboBox_Language.SelectedItem;
                    flowLayoutPanel3.Controls.Add(button);
                    myList.Add(Computer);
                    MessageBox.Show(Computer + "added");
                }

In my GUI, if Users want to edit a configuration, he click on the new button representing the configuration and all choices are back, like :

comboBox_OS.SelectedItem = button.CustomOS; 
comboBox_Language.SelectedItem = button.CustomLanguage;

Is that possible to create my custom attribute like button.CustomOS and button.CustomLanguage ?

Regards

It is possible and quite easy. You just derive a new class from the original Button and declare two new Properties. I included the code into a simple example.

using System;
using System.Windows.Forms;

namespace StackOverflow
{
    public partial class FormMain : Form
    {
        public FormMain()
        {
            InitializeComponent();
        }

        private void cbOS_SelectedIndexChanged(object sender, EventArgs e)
        {
            //Save selection.
            ComboBox cb = (ComboBox)(sender);
            btn1.CustomOS = cb.SelectedItem.ToString();
        }

        private void btnSelect_Click(object sender, EventArgs e)
        {
            //Restore selection on click.
            MyButton btn = (MyButton)(sender);
            cbOS.SelectedItem = btn.CustomOS;
        }

        //Declare a new class deriving from the original Button.
        public class MyButton : Button
        {
            public String CustomOS { get; set; }    
            public String CustomLanguage { get; set; }
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM