2

I have a Drop Down List . I need the value of my DDL when the index changes.So i do this :

 private void CMBGroup_SelectedIndexChanged(object sender, EventArgs e)
        {
           int id=int.Parse(CMBGroup.SelectedValue.ToString());
           //do something with id
       }

In form load i fetch my data :

        goodGroups=objGoodGroupRepositoy.GetAll().ToList();
        CMBGroup.DataSource = goodGroups;
        CMBGroup.ValueMember = "Id";
        CMBGroup.DisplayMember = "Name";

I have such data in my database :

id serial    name
1   121    g1
2   123    g2

But i got this error before loading my form :

Input string was not in a correct format

I got this error in here in indexchange event of DDL

int id=int.Parse(CMBGroup.SelectedValue.ToString());

The model :

public partial class GoodGroup
    {
        public GoodGroup()
        {
            this.Goods = new HashSet<Good>();
        }

        public int Id { get; set; }
        public string Serial { get; set; }
        public string Name { get; set; }

        public virtual ICollection<Good> Goods { get; set; }
    }
Ehsan Akbar
  • 6,977
  • 19
  • 96
  • 180

2 Answers2

6

You should set the DisplayMember and ValueMember properties before the DataSource.

When the DataSource is changed, or when DisplayMember or ValueMember is changed after DataSource has been set, the binding infrastructure forces the control to rebind

Another way is to unsubscribe / subscribe to the event when modifying datasource.

NicoD
  • 1,179
  • 8
  • 19
  • i used this code in another page and it worked why ?i mean i set the value and display property after datasource? – Ehsan Akbar Jun 26 '14 at 15:29
  • 1
    I've updated my answer. In your case hard to guess. Maybe you use a simple datasource and the toString() method is ok. Maybe you unsubscribe the SelectedIndexChanged event ? – NicoD Jun 26 '14 at 15:37
  • Yes exactly iunsubscribe the SelectedIndexChanged event,by the way thank you – Ehsan Akbar Jun 26 '14 at 15:38
0

Instead of handling SelectedIndexChanged event, you can just handle the SelectionChangeCommitted event.

When you handle this event, you don't have to unsubscribe and resubscribe the event handler because it will only fire after you have changed the value of the combo box by selecting-not after you change the datasource.

John Evans Solachuk
  • 1,953
  • 5
  • 31
  • 67