Home > OS >  DataGridView DataSource can't be added to
DataGridView DataSource can't be added to

Time:08-12

This part of my code is responsible for adding new items to my BindingList<DevicePropertyTable> called DeviceStorage

public void StoreDevice(string deviceName)
        {
            var device = new DevicePropertyTable()
            {
                IEEE = deviceName,
                StateRegister = ""
            };

            DeviceStorage.Add(device);
        }

The problem is, the code hangs on the .Add, because the DGV's DataSource has been assigned as this list.

If I assign it after I filled it with some data it displays correctly, but then I can'd add new items yet again. The DGV seems to hold my List hostage.

How would I go about making the list accessible? Since this code is in a seperate class from the Form, I can't access the DGV directly to just set the DataSource to null.

CodePudding user response:

As @user18387401 said in the comments above, this is a problem with accessing the UI thread from a different thread. I got around this by adding 2 methonds and 2 invokers to my From:

public void ReleaseTableDataBindInvoker()
{
    mapping_table.Invoke(new MethodInvoker(ReleaseTableDataBind));
}

public void ReleaseTableDataBind()
{
    mapping_table.DataSource = null;
}

public void BindTableDataInvoker()
{
    mapping_table.Invoke(new MethodInvoker(BindTableData));
}

public void BindTableData()
{
    mapping_table.DataSource = DeviceTableStorage.getInstance().DeviceStorage;
}

note: mapping_table is the name of my DGV

and then I passed a reference to the form when starting the seperate thread, to access these methods. Then I simply release the bind, add my data and re-bind the table.

public static void HandleIncomingMessages(Form1 mainFrom)
        {
           //some code here
             
            mainFrom.ReleaseTableDataBindInvoker();
            DeviceTableStorage.getInstance().StoreDevice(device_friendly_name);
            mainFrom.BindTableDataInvoker();
        }
  • Related