Search code examples
c#winformscombobox

Can i change combobox items in c# runtime?


I have a windows form app and a there is a combobox, which is filled from a txt file.

        List<string> lines = System.IO.File.ReadLines(path).ToList();

        foreach (string l in lines)
        {
            combobox.Items.Add(l);
        }

As a result of a button, i would like to change the path. Is it possible? I changed the path but nothing happened, i think because i need to call the constructor again, but the button is in a different window, the combobox is in another window.


Solution

  • You can create a method that takes a path to your txt file as a parameter. Then you can call that method on Form_Load and Button_Click with different paths.

        private void Form1_Load(object sender, EventArgs e)
        {
            populateCombo(path);
        }
    
        private void populateCombo(string path)
        {
            comboBox1.Items.Clear();
            List<string> lines = System.IO.File.ReadLines(path).ToList();
    
            foreach (string line in lines)
            {
                comboBox1.Items.Add(line);
            }
        }
    
        private void button1_Click(object sender, EventArgs e)
        {
            populateCombo(differentPath);
        }