绑定到List后,ComboBox.SelectedValue会搞乱

时间:2010-07-21 20:56:34

标签: c# winforms data-binding combobox

我在这里失去理智......

我在表单上有一个ComboBox,其中一个属性已更改,Sorted = true。

这个属性搞乱了SelectedValue,我想知道原因。

看一下代码(你可以把它粘贴到新的WinForms项目中,它会在添加一个组合框后工作):

    private void Form1_Load(object sender, EventArgs e)
    {
        List<ColumnFilter> ColumnFilters = new List<ColumnFilter>();
        ColumnFilters.Add(new ColumnFilter("Ope_OpeID", "Ope_OpeID", ColumnFilterType.DataGridViewHidden));
        ColumnFilters.Add(new ColumnFilter("Ope_Kod", "Ope_Kod", ColumnFilterType.DataGridViewHidden));
        ColumnFilters.Add(new ColumnFilter("Ope_Imie", "Ope_Imie", ColumnFilterType.DataGridViewHidden));
        ColumnFilters.Add(new ColumnFilter("Ope_Nazwisko", "Ope_Nazwisko", ColumnFilterType.DataGridViewHidden));

        comboBox1.DataSource = ColumnFilters;
        comboBox1.DisplayMember = "Description";
        comboBox1.ValueMember = "Expression";
    }

    private void comboBox1_SelectionChangeCommitted(object sender, EventArgs e)
    {
        MessageBox.Show(comboBox1.SelectedValue.ToString());
    }
}
public enum ColumnFilterType
{
    DataGridView = 1,
    DataGridViewHidden = 2,
    DataTable = 3
}

public struct ColumnFilter
{
    private string description;
    private string expression;
    public string Description
    {
        get { return description; }
        set { description = value; }
    }
    public string Expression
    {
        get { return expression; }
        set { expression = value; }
    }
    public readonly ColumnFilterType Type;
    public ColumnFilter(string description, string expression, ColumnFilterType type)
    {
        this.description = description;
        this.expression = expression;
        this.Type = type;
    }
    public override string ToString()
    {
        return description;
    }
}

正如您所看到的,我手动将4个结构添加到List中,而在SelectionChangeCommited事件中,我想显示所选结构的当前值。

所以当我选择Ope_OpeID时,我想要看一个值Ope_OpeID,当我选择Ope_Imie时,我希望看到值Ope_Imie。换句话说,value必须等于显示的文本。

问题在于,例如当我选择Ope_Imie时,值为Ope_OpeID! 当我选择Ope_OpeID时,值为Ope_Nazwisko。我不知道为什么这样有效。

“搞笑”(浪费了两个小时后不那么好笑..)事情就是当我在列表中添加不同的项目时:

        ColumnFilters.Add(new ColumnFilter("1Ope_OpeID", "1Ope_OpeID", ColumnFilterType.DataGridViewHidden));
        ColumnFilters.Add(new ColumnFilter("2Ope_Kod", "2Ope_Kod", ColumnFilterType.DataGridViewHidden));
        ColumnFilters.Add(new ColumnFilter("3Ope_Imie", "3Ope_Imie", ColumnFilterType.DataGridViewHidden));
        ColumnFilters.Add(new ColumnFilter("4Ope_Nazwisko", "4Ope_Nazwisko", ColumnFilterType.DataGridViewHidden));

它有效。因此,排序确实存在问题,它是否只对第一个字符排序???

感谢您的时间。

1 个答案:

答案 0 :(得分:1)

Sorted属性不适用于数据绑定组合框。请参阅备注部分here

您可以选择使ColumnFilter实现IComparable,然后对List&lt;&gt;进行排序。直接