Ricardo De Oliveira
Ricardo De Oliveira

Reputation: 1

Bindinglist bound to datagridview throws error System.InvalidOperationException

I'm using C#, Winforms on .NET 4.7.2, and my project has a dataGridView bound to a BindingList<Frame>.

When I add dynamically the first object to the list, it throws System.InvalidOperationException with no more explanations why.

internal class Frame : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    private string pgn; 
    private string b0;
    private string b1;

    public string PGN
    {
        get => pgn;
        set { pgn = value; OnPropertyChanged(); }
    }

    [DisplayName("Byte 0")]
    public string B0
    {
        get => b0;
        set { b0 = value; OnPropertyChanged(); }
    }

    [DisplayName("Byte 1")]
    public string B1
    {
        get => b1;
        set { b1 = value; OnPropertyChanged(); }
    }

    protected void OnPropertyChanged([CallerMemberName] string name = null)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
    }
}

public partial class fmVisualizer : Form
{
    BindingList<Frame> Frames;

    public fmVisualizer ()
    {
        InitializeComponent();

        Frames = new BindingList<Frame>();

        formPrincipal.FrameReceived += FrameReceived; //some event will add new data

        dgv.DataSource = Frames; //my dataGridView 

    }

    private void FrameReceived(string somePgn) 
    {       
        Frame found = Frames.Where(x => x.PGN == somePgn).FirstOrDefault();

        if (found != null)
        {
           //...
        }
        else
        {
            Frame newFrame = new Frame()
            {
                PGN = somePgn,
                B0 = "something1...",
                B1 = "something2..."
            };

            // this line throws "System.InvalidOperationException"
            Frames.Add(newFrame); 
        }
    }
}

I don't understand what may be happening. One weird thing I observed was that when it throws the error, my list, which should have zero elements since it was disabled to add the first data, it actually has one element with all fields and properties set to null.

Other thing was that if I erase the line

dgv.DataSource = Frames;

it works fine, my first element is added, and there's no null element inside the list.

Upvotes: 0

Views: 81

Answers (0)

Related Questions