c# - ComboBox 在更改 DataSource 后记住 SelectedIndex

标签 c# winforms combobox

背景

最近,我观察到 Winform ComboBox 控件的两个不良行为:

  1. DataSource 属性设置为新对象会将 SelectedIndex 值设置为 0
  2. DataSource 属性设置为以前使用的对象“记住”以前的 SelectedIndex

下面是一些示例代码来说明这一点:

private void Form_Load(object sender, EventArgs e)
    {
        string[] list1 = new string[] { "A", "B", "C" };
        string[] list2 = new string[] { "D", "E", "F" };

        Debug.Print("Setting Data Source: list1");
        comboBox.DataSource = list1;

        Debug.Print("Setting SelectedIndex = 1");
        comboBox.SelectedIndex = 1;

        Debug.Print("Setting Data Source: list2");
        comboBox.DataSource = list2;

        Debug.Print("Setting SelectedIndex = 2");
        comboBox.SelectedIndex = 2;

        Debug.Print("Setting Data Source: list1");
        comboBox.DataSource = list1;

        this.Close();
    }

    private void comboBox_SelectedIndexChanged(object sender, EventArgs e)
    {
        Debug.Print("Selected Index Changed, SelectedIndex: {0}", comboBox.SelectedIndex);
    }

    private void comboBox_DataSourceChanged(object sender, EventArgs e)
    {
        Debug.Print("Data Source Changed, SelectedIndex: {0}", comboBox.SelectedIndex);
    }

这会产生以下输出:

Setting Data Source: list1
Data Source Changed, SelectedIndex: -1
Selected Index Changed, SelectedIndex: 0
Setting SelectedIndex = 1
Selected Index Changed, SelectedIndex: 1
Setting Data Source: list2
Data Source Changed, SelectedIndex: 1
Selected Index Changed, SelectedIndex: 0
Setting SelectedIndex = 2
Selected Index Changed, SelectedIndex: 2
Setting Data Source: list1
Data Source Changed, SelectedIndex: 2
Selected Index Changed, SelectedIndex: 1

最后一条调试语句特别有趣。

问题

这怎么可能,是否有办法防止这种行为?

ComboBox 的“内存”是无限期的,还是由易受垃圾回收影响的对象支持?前者表示调整 DataSource 导致内存消耗,后一种情况表示在设置 DataSource 时 ComboBox 的行为不可预测。

最佳答案

我不知道 DataSource 对象的所有内部工作原理,但可能是 ComboBox 为列表保留了关联的 CurrencyManager 信息,这使得它可以在 DataSource 重新连接时记住之前的位置。

您可以通过将列表包装在新的 BindingSource 对象中来避免此行为:

comboBox.DataSource = new BindingSource(list1, null);

这会将位置属性默认设置回零(如果有记录)。

关于c# - ComboBox 在更改 DataSource 后记住 SelectedIndex,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22413908/

相关文章:

c# - 如何从文本框中删除CSS?

.net - 支持 Windows 窗体中的 OpenFileDialog 和 FolderBrowserDialog 中的重定向驱动器

java - Eclipse插件: make Combo to handle Enter key

c# - 来自同一数据集的多个 ComboBox 控件

c# - 使 Propertygrid 在运行时显示绑定(bind)的属性符号

c# - C#中的多维数组访问性能

c# - 关闭以其他用户身份以编程方式启动的资源管理器

winforms - 由于Microsoft.ReportingServices.Rendering.RichText.CachedFont GetFont,ReportViewer崩溃

c# - Winforms 中可调整大小的文本框

c# - 如何创建尽可能多的相同数据绑定(bind)组合框,但从相同的字段名称中提取不同的值?