Search code examples
c#comboboxpass-by-reference

C# Passing ComboBox to a function of separate class


I have to list Companies in a desktop application again and again in diferent forms. That's why I wanted to make a common functions class to list companies in ComboBox on diferent forms. I am trying to pass ComboBox object to functions. But I am unable to do so. Following is the code which I am trying.

   CommonFunctions cmFunc = new CommonFunctions();
   ComboBox cmbx = cmbCompany;
   cmFunc.listCompanies(ComboBox cmbx);

cmbCompany is the ComboBox where companies will list.

Any suggestion or help highly appreciated.


Solution

  • If I understand correctly, you want to use a Delegate to fill a combo box on different forms.

    The code below works and fills a ComboBox on a Windows Form, using a delegate. comboBox1 is a ComboBox on this form.

    public partial class Form1 : Form
    {
        delegate void FilComboDelegate(ComboBox comboBox);
    
        public Form1()
        {
            InitializeComponent();
        }
    
        private void Form1_Load(object sender, EventArgs e)
        {
            FilComboDelegate fillComboHandler;
    
            fillComboHandler = FillCombo;
    
            fillComboHandler(comboBox1);
        }
    
        private static void FillCombo(ComboBox comboBox)
        {
            string [] companies = {"Company 1", "Company 2", "Company 3"};
    
            comboBox.Items.Clear();
    
            foreach(var company in companies)
                comboBox.Items.Add(company);
        }
    }