I am using a datagridview in my form, which's data source is a binding source control. In the current changed event of the binding source control I am trying to hide the rows in the datagridview. Then I get the following error,
Row associated with the currency manager's position cannot be made invisible.
The code i used is given below,
rowClicked = reportsBindingSource.Position
for (int i = 0; i < dgvItems.Rows.Count; i++)
{
try
{
if (rowClicked != i)
{
dgvItems.Rows[i].Visible = false;
}
}
catch (Exception)
{
throw;
}
}
What is wrong with the code? I tried using the below but nothing works,
CurrencyManager currencyManager1 = (CurrencyManager)BindingContext[dgvItems.DataSource];
currencyManager1.SuspendBinding();
dgvItems.Rows[i].Visible = false;
currencyManager1.ResumeBinding();
and
dgvItems.CurrentCell= null
dgvItems.Rows[i].Visible = false;
Is there any solution for this?
Well, as indicated by the exception, hiding rows is not supported in data bound mode. So in order to achieve your goal, you should use some data binding mechanism.
From data binding perspective, "hiding" rows is equivalent of filtering the source list. Since the BindingSource
component can act as both single item and list data source, the easiest is to use intermediate BindingSource
containing the Current
of the primary source, like this:
BindingSource bindingSource; // Your current component used as DataSource for the dataGridView
var currentSource = new BindingSource { DataSource = bindingSource.Current };
dataGridView.DataSource = currentSource;
bindingSource.CurrentChanged += (_sender, _e) => currentSource.DataSource = bindingSource.Current;