OMGKurtNilsen
OMGKurtNilsen

Reputation: 5098

Bindable ReadOnly List

I have a Ticket class containing a collection of TicketLine objects. I want to bind this collection to a DataGridView but without letting anything but the Ticket class add and remove items from it.

So far I have used a BindingList and implementet INotifyPropertyChanged in TicketLine, but this exposes Add and Remove methods on the list itself.

How do I this collection to a DataGridView without exposing other Add/Remove methods than those in the Ticket class?

Upvotes: 1

Views: 339

Answers (2)

dzendras
dzendras

Reputation: 4751

What I can think of is to implement IBindingList interface using decorator pattern by delegating all calls to wrapped read/write BindingList. The only exceptions are:

  • AllowEdit/Add/Remove members which return false.
  • Add/Remove methods which throw InvalidOperationException (or NotSupportedException) That's how read-only aspect is assured.

Once you create this read-only wrapper, you pass it to DataGridView. Provided that it respects the contract (I assume it does :)) it should disallow modifying the underlying list.

Once I faced the same problem and the solution was too troublesome to implement. Mainly because of loss of generics and the amount of work it required. I hope it helps, though.

Upvotes: 1

Sebastian Negraszus
Sebastian Negraszus

Reputation: 12215

You could hide the list and only expose an IEnumerable property:

public class Ticket : INotifyPropertyChanged
{
    private List<TicketLine> ticketLines;

    public IEnumerable<TicketLine> TicketLines
    {
        get { return ticketLines.AsReadOnly(); }
    }

    public void Add(TicketLine ticketLine)
    {
        ticketLines.Add(ticketLine);
        OnPropertyChanged("TicketLines");
    }

    public event PropertyChangedEventHandler PropertyChanged;

    private void OnPropertyChanged(string propertyName)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}

Upvotes: 0

Related Questions