Binding objects DataGridView C#

前端 未结 4 496
南旧
南旧 2020-12-10 08:54

i have a DataGridView and a list of objects that i would like to show.

The Objects are these:

public class Entity
{
    public int ID { get; set; }
}         


        
4条回答
  •  孤城傲影
    2020-12-10 09:31

    All that code in the CellFormatting and BindProperty methods seems excessive. I mean, something's got to basically do that, but I think it's already been done. I implement INotifyPropertyChanged in the object I want to bind to a grid row, and I put those objects into a BindingList. The BindingList is directly used as the datasource for the grid.

    This approach means a little more typing in the basic entity class you're mapping to the grid row but I think it saves a lot more elsewhere. To implement INotifyPropertyChanged in your class:

    public class Entity: INotifyPropertyChanged
        {
            public event PropertyChangedEventHandler PropertyChanged;
            public Entity()
            {
                Selected = false;
            }
    
            private bool _selected;
            public bool Selected
            {
                get
                {
                    return _selected;
                }
                set
                {
                    if (_selected != value)
                    {
                        _selected = value;
                        OnPropertyChanged(nameof(Selected));
                    }
                }
            }
    
            protected virtual void OnPropertyChanged(string propertyName)
            {
                if (PropertyChanged != null)
                {
                    PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
                }
            }
        }
    

    Then put a column in your grid and give it a DataPropertyName of "Selected" to match the name of the property in Entity that should appear in that column. Obviously add whatever properties you want to your grid, matching the properties of the entity. The key is to be sure to implement the property setter with the call to PropertyChanged.

    This gets you two-way binding between the grid and your list of objects.

    My personal opinion: even this is way too much code. I find myself constantly writing these kinds of things that do the obvious: take a property by name and map it to something else that knows that name (like the grid column in this example). It's just beyond my comprehension why these things don't just automatically hook up. A list and grid should have enough sense to figure this basic arrangement on their own. zero lines of code. Ok, one line of code. Grid.Datasource = List. So this is how I do it. I'd love to know a less lines of code way to do this.

提交回复
热议问题