0

Problem Statement:

I have a Form A and here i am calling one API and it is taking few seconds to complete its operation. So, in this duration the user is closing the Form A. Due to this the object created in Form A gets disposed.

When the response comes back from API and try to call DataBinding() method it throws this exception: System.InvalidOperationException: 'Databinding cannot occur unless a BindingContext or BindingContext Control has been specified.'

Code:

public partial class FormA{
    private async void BindData(){
        var response = await _service.APICall(id);
        ultraComboEditor.DataSource = response;
        ultraComboEditor.DataBind(); //This throws the exception.
    }
}

Question:

How to avoid this exception?

I can add a try catch block and avoid this exception, but it is not a good approach. So, is there any better solution to this?

Indranil
  • 2,229
  • 2
  • 27
  • 40
  • 1
    `if (formA != null && !formA.IsDisposed) { }`. But, is that API call async? Does it accept a CencellationToken? + What is `formA`? Not a Form, since it doesn't have a `DataSource` property. A little more context, maybe? – Jimi May 29 '20 at 15:02
  • Hi @Jimi, yes the API call is async. I have updated the code. Hope this helps. – Indranil Jun 01 '20 at 04:08

1 Answers1

0

I found the perfect solution to this problem. The root cause of the problem was we are waiting for task to complete on form close.

Reference: Awaiting Asynchronous function inside FormClosing Event

Solution:

The solution to my problem was to add a boolean variable(eg: _acyncClose) and set it to true on form closing event then after the API call I am checking for this property.

Code:

public partial class FormA{
    private bool _asyncClose = false;

    private async void BindData(){
        var response = await _service.APICall(id);
        if (_asyncClose) return;
        ultraComboEditor.DataSource = response;
        ultraComboEditor.DataBind(); //This throws the exception.
    }

    private void Form_Closing_Event(){
        _asyncClose = true;
    }
}
Indranil
  • 2,229
  • 2
  • 27
  • 40