My original idea was to have you create a list of the ReadOnly
columns for each DataGridView
. Then have you reset those columns from that list, either in the ReadOnlyChanged
event for each DataGridView
(too much code copy), or send those lists as a second parameter to the common code method and reset them there. But then I thought, what if you only have access to the Common Code?
This led me to the following generic solution. The idea remains the same: each DataGridView
will have a list of ReadOnly
columns. But this list will be directly attached to the DataGridView
via the Tag
property instead of as code bloat in the dgv's (perhaps unreachable) parent class.
If your common code method looks something like this:
public void DoStuff(DataGridView dgv)
{
if (dgv.ReadOnly)
{
dgv.ReadOnly = false;
// Do related stuff.
}
else
{
dgv.ReadOnly = true;
// Do other related stuff.
}
// Do common stuff.
}
Make these changes to Save / Load the ReadOnly
columns:
public void DoStuff(DataGridView dgv)
{
if (dgv.ReadOnly)
{
dgv.ReadOnly = false;
// Load the saved ReadOnly columns.
List<DataGridViewColumn> rocs = dgv.Tag as List<DataGridViewColumn>;
if (rocs != null)
{
foreach (DataGridViewColumn roc in rocs)
{
roc.ReadOnly = true;
}
}
// Do related stuff.
}
else
{
// Save the ReadOnly columns before the DGV ReadOnly changes.
List<DataGridViewColumn> rocs = new List<DataGridViewColumn>();
foreach (DataGridViewColumn col in dgv.Columns)
{
if (col.ReadOnly)
{
rocs.Add(col);
}
}
dgv.Tag = rocs;
dgv.ReadOnly = true;
// Do other related stuff.
}
// Do common stuff.
}