简体   繁体   中英

Binding a DataGridView and Textbox to the same Datable gives me a 'two binding' error

I have two DataTables, and each one is bound to its own DataGridView and RichTextBox.

So for dataTable1, I have bound dgvFirstOne and rtbFirstOne. For dataTable2, I have bound dgvSecondOne and rtbSecondOne.

Opening the form and using the DataGridViews work perfectly. No issue there. However, when I close the form ( this.close() ), I get the following error:

'This causes two bindings in the collection to bind to the same property.'

I suspect that this is because I have a richtextbox and a datagridview bound to the same datatable.

dgvFirstOne.DataSource = Form1.dataTable1;
rtbFirstOne.DataBindings.Add("Text", dataTable1, "DataColumn");

dgvSecondOne.DataSource = Form1.dataTable2;
rtbSecondOne.DataBindings.Add("Text", dataTable2, "DataColumn");

This strikes me as particularly odd, as in another form, I have a DataTable and a DataGridView and RichTextBox bound in the same manner, with no issues.

I have tried binding it this way as well, but with the same result:

this.bsFirstOne = new BindingSource();
bsFirstOne.DataSource = dataTable1;
rtbFirstOne.DataSource = bsFirstOne;
rtbFirstOne.DataBindings.Add("Text", rtbFirstOne, "Data", true, DataSourceUpdateMode.OnPropertyChanged);
bsFirstOne.BindingComplete += new BindingCompleteEventHandler(bsFirstOne_BindingComplete);

this.bsSecondOne = new BindingSource();
bsSecondOne.DataSource = dataTable2;
dgvSecondOne.DataSource = bsSecondOne;
rtbSecondOne.DataBindings.Add("Text", bsSecondOne, "Data", true, DataSourceUpdateMode.OnPropertyChanged);
bsSecondOne.BindingComplete += new BindingCompleteEventHandler(bsSecondOne_BindingComplete);

Does anyone know what's going on?

Every control can have only on binding at a time. That's why before assigning a binding source, just clear old binding using Clear() method:

dgvFirstOne.DataSource = Form1.dataTable1;
rtbFirstOne.DataBindings.Clear();
rtbFirstOne.DataBindings.Add("Text", dataTable1, "DataColumn");

dgvSecondOne.DataSource = Form1.dataTable2;
rtbSecondOne.DataBindings.Clear();
rtbSecondOne.DataBindings.Add("Text", dataTable2, "DataColumn");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM