如何让ListBox与ComboBox共用数据源且实现独立操作?
解决ComboBox与ListBox绑定同一数据源时选择同步的问题
问题根源:当你直接把同一个List<string>对象同时设置为ComboBox和ListBox的DataSource时,两个控件会共享默认的绑定上下文(BindingContext),导致选择操作互相同步。
以下是两种可行的解决方法:
方法1:用BindingSource分别包装数据源
给每个控件创建独立的BindingSource实例,以此隔离绑定上下文,这样两个控件的选择状态就不会互相影响:
Excel.Application xlApp = new Excel.Application(); Excel.Workbook xlWorkBook = xlApp.Workbooks.Open(excelFilePath); //List<string> sheetList = new List<string>(); <- 已提前声明 foreach (Excel.Worksheet xlWorkSheet in xlWorkBook.Worksheets) { sheetList.Add(xlWorkSheet.Name); } // 为ComboBox创建独立BindingSource var comboBinding = new BindingSource(); comboBinding.DataSource = sheetList; comboBox1.DataSource = comboBinding; // 为ListBox创建独立BindingSource var listBinding = new BindingSource(); listBinding.DataSource = sheetList; listBox1.DataSource = listBinding; // 关闭Excel并释放资源 xlWorkBook.Close(false); xlApp.Quit(); Marshal.ReleaseComObject(xlWorkBook); Marshal.ReleaseComObject(xlApp);
方法2:为每个控件创建数据源副本
直接给两个控件绑定数据源的不同实例,这样它们操作的是各自的集合,自然不会同步选择:
Excel.Application xlApp = new Excel.Application(); Excel.Workbook xlWorkBook = xlApp.Workbooks.Open(excelFilePath); //List<string> sheetList = new List<string>(); <- 已提前声明 foreach (Excel.Worksheet xlWorkSheet in xlWorkBook.Worksheets) { sheetList.Add(xlWorkSheet.Name); } // 绑定各自的集合副本 comboBox1.DataSource = new List<string>(sheetList); listBox1.DataSource = new List<string>(sheetList); // 关闭Excel并释放资源 xlWorkBook.Close(false); xlApp.Quit(); Marshal.ReleaseComObject(xlWorkBook); Marshal.ReleaseComObject(xlApp);
内容的提问来源于stack exchange,提问作者sharpnado
相关产品推荐
相关产品推荐

