views:

152

answers:

0

I'm using a DataGridViewComboBoxColumn with a data source and specifying the DisplayMember and ValueMember. Some of the items have the same display name but their values are different. When the user selects one of those in the ComboBox dropdown, it always returns the first item that has the same name, completely ignoring the actual item. Is there anyway to get the right item?

Below sample has a DataGridView with the DataGridViewComboBoxColumn and a TextBox to output the cells value after it's been entered.

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        var items = new List<ComboItem>();
        for (int i = 0; i < 5; i++)
            items.Add(new ComboItem("test", i));
        GridColumnCombos.DisplayMember = "Name";
        GridColumnCombos.ValueMember = "Item";
        GridColumnCombos.DataSource = items;
        //GridColumnCombos.ValueType = typeof(int);
    }

    private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e)
    {
        if (e.RowIndex >= 0 && e.ColumnIndex == GridColumnCombos.Index)
        {
            var item = (int)dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value;
            mTextBox.Text = item.ToString();
        }
    }
}

public class ComboItem : IEquatable<ComboItem>
{
    public ComboItem(string name, int item)
    {
        Name = name;
        Item = item;
    }

    public string Name { get; set; }
    public int Item { get; set; }

    public override string ToString()
    {
        return Name;
    }

    #region IEquatable<ComboItem> Members

    public bool Equals(ComboItem other)
    {
        if (other == null)
            return false;
        return Item == other.Item;
    }

    #endregion
}