I have a routine which converts all the data in a DataGridView to a corresponding DataTable. I want to extend this method to incorporate the ability to convert just the selected range of the DataGridView. I can clearly do this using basic logic if (bIsSelection) /*Do stuff*/ else /*Do other stuff*/ but I would like to use generics here. The problem is that the full DataGridView range is a DataGridViewColumnCollection and the selected range will be a DataGridViewSelectedColumnCollection and C# does not seem to like any conversion between the two, or allow implicit typing in the case of generics.
The first part of my code was
public static DataTable BuildDataSetFromDgv(DataGridView _dataGridView,
string strTabName)
{
DataTable dt = new DataTable();
dt.TableName = strTabName;
foreach (DataGridViewColumn col in _dataGridView.Columns)
dt.Columns.Add(col.DataPropertyName, col.ValueType);
and I have attempted
public static DataTable BuildDataSetFromDgv<T>(DataGridView _dataGridView,
string strTabName, ICollection<T> _columnColl, ICollection<T> _rowColl)
{
DataTable dt = new DataTable();
dt.TableName = strTabName;
//foreach (DataGridViewColumn col in _dataGridView.Columns)
foreach (DataGridViewColumn col in _columnColl)
dt.Columns.Add(col.DataPropertyName, col.ValueType);
which does not work due to the implicit conversion, and changing _columnColl to _columnColl as DataGridView[Selected]ColumnCollection defeats the objective.
How do I make this work with generics in this case?
Thanks for your time.
I am not sure why you need a generic one – both are collection of
DataGridViewColumn. For example, why below shouldn’t work for you