[c#] BindingList를 DataGridView에 바인딩할 때 생기는 버그들

아래의 코드는 클래스가 담긴 BindingList를 DataGridView에 바인딩하는 예제다. 그저 바인딩만 했을 뿐이지만 빈 엘리먼트가 바인딩 리스트에 저절로 만들어지고 데이터 그리드 뷰에 출력까지 된다.

이 문제를 우회하는 데에는 두 개의 방법들이 있다.

1. Form_Load 아닌 이벤트에서 바인딩을 한다.
2. DataGridView.AllowUserToAddRows를 false로 한다.

class Class1
{
    public int Int { get; set; }
}

BindingList<Class1> Class1s = new();

private void Form1_Load(object sender, EventArgs e)
{
    dataGridView1.DataSource = Class1s;
}

아래의 버그는 위의 버그와 연결되어 있다. 위 코드에 덧붙여 Form_Click 이벤트에서 BindingList.Add 메서드를 실행하면 System.InvalidOperationException: ‘Operation is not valid due to the current state of the object.’ 예외로 처리된다.

private void Form1_Click(object sender, EventArgs e)
{
    Class1 class1 = new();

    class1.Int = 1;

    Class1s.Add(class1); // exception
}

우회 방법은 위와 같다. 폼 클릭 이벤트 말고 Button_Click에서 실행하면 잘 된다.