c# - How to bind a list count to a label -


i have datagridview binding list , label showing number of records. run same problem khash had. (so steal title). add or delete operations on grid won't update label.

enter image description here

based on sung's answer, facade wrapper, create custom list inheriting bindinglist , implementing inotifypropertychanged.

public class countlist<t> : bindinglist<t>, inotifypropertychanged {         protected override void insertitem(int index, t item)     {         base.insertitem(index, item);         onpropertychanged("count");     }      protected override void removeitem(int index)     {         base.removeitem(index);         onpropertychanged("count");     }      public event propertychangedeventhandler propertychanged;     private void onpropertychanged(string propertyname)     {         if (propertychanged != null)             propertychanged(this, new propertychangedeventargs(propertyname));     } } 

however, throw exception when binding.

cannot bind property or column count on datasource. parameter name: datamember

below binding code:

private countlist<person> _list;  private void form1_load(object sender, eventargs e) {     _list = new countlist<person>();     var binding = new binding("text", _list, "count");     binding.format += (sender2, e2) => e2.value = string.format("{0} items", e2.value);     label1.databindings.add(binding);     datagridview1.datasource = _list; }  public class person {     public int id { get; set; }     public string name { get; set; } } 

any suggestions appreciated. thank you.

in fact, simpler think!

microsoft has created bindingsource control, so, need use , handle bindingsource event update label:

    public class person     {         public int id { get; set; }         public string name { get; set; }     }      private bindingsource source = new bindingsource();      private void form1_load(object sender, eventargs e)     {         var items = new list<person>();         items.add(new person() { id = 1, name = "gabriel" });         items.add(new person() { id = 2, name = "john" });         items.add(new person() { id = 3, name = "mike" });         source.datasource = items;         gridcontrol.datasource = source;         source.listchanged += source_listchanged;      }      void source_listchanged(object sender, listchangedeventargs e)     {         label1.text = string.format("{0} items", source.list.count);     } 

Comments

Popular posts from this blog

blackberry 10 - how to add multiple markers on the google map just by url? -

php - guestbook returning database data to flash -

delphi - Dynamic file type icon -