Search code examples
c#.netvisual-studiocomboboxlistbox

a listbox and a combobox with same source but I need them acting seperately


I need the combobox and listbox to populate from the same source but act seperately. If select an item on the listbox it switches the item on the combobox on the following code:

        Excel.Application xlApp = new Excel.Application();
        Excel.Workbook xlWorkBook = xlApp.Workbooks.Open(excelFilePath);

        //List<string> sheetList = new List<string>(); <- this field was created before
        foreach (Excel.Worksheet xlWorkSheet in xlWorkBook.Worksheets)
        {
            sheetList.Add(xlWorkSheet.Name);
        }

        comboBox1.DataSource = sheetList;
        listBox1.DataSource = sheetList;

        // Close the Excel workbook and release resources
        xlWorkBook.Close(false);
        xlApp.Quit();


        Marshal.ReleaseComObject(xlWorkBook);
        Marshal.ReleaseComObject(xlApp);

Solution

  • The problem is because they use the same source.

    The solution is simple, creating and copying a source for them alone solves the problem.

    For example:

    var list2 = new List<string>();
    foreach (string s in sheetList)
    {
        list2.Add(s);
    }
    
    comboBox1.DataSource = sheetList;
    listBox1.DataSource = list2;