Home > Mobile >  Winforms reset binding when datasource change
Winforms reset binding when datasource change

Time:07-09

Affter change datasource of datagridview, textbox binding not working. How can i fix this?

private void loadData()
{
    dataGridView.DataSource = m_db.getData_wProc(); // Datatable
    txtID.DataBindings.Add("Text", dataGridView.DataSource, "Id");
}

Note: not using

txtID.DataBindings.Clear();

CodePudding user response:

  BindingSource bindingSource = new BindingSource();
  bindingSource.DataSource = null;
  dataGridView.DataSource = bindingSource;

or

public static void DynamicBind<T>(this DataGridView dataGrid, IList<T> source)
where T : class
{
    BindingSource _bindingSource = null;

    if (dataGrid.DataSource is BindingSource)
    {
        _bindingSource = (BindingSource)dataGrid.DataSource;
        _bindingSource.AllowNew = true;

        foreach (T entity in source)
        {
            _bindingSource.Add(entity);
        }
    }
    else
    {
        BindingList<T> _bindinglist = new BindingList<T>(source);
        _bindingSource = new BindingSource(_bindinglist, null);
        dataGrid.DataSource = _bindingSource;
    }
}

CodePudding user response:

Thanks @Zhiwei. That correct!

bool isBinding = true;
BindingSource bindingSource = new BindingSource();
...
private void loadData()
{
    bindingSource = m_db.getData_wProc(); // Datatable
    if(isBinding){
          dataGridView.DataSource = bindingSource;
          txtID.DataBindings.Add("Text", bindingSource, "Id");

          isBinding = false;
    }else{
          bindingSource.ResetBindings(false);
    }
}
  • Related