Lets say, we have 10 columns in one datagridview. I have 20 rows of data in these 10 columns.
Dynamically, I'm hiding (setting the .Visible property of the column to false) a few columns - say column 1, 2, 4, 5.
Now I want to copy the contents of the columns which are visible (20 rows of dat开发者_运维百科a, 6 visible columns - 3, 6, 7, 8, 9, 10) to a new datagridview.
Any suggestions / advise / links?
I've researched this forum and could not find a post discussing about copying a subset of columns from one datagridview to another.
thanks.
Try this (you didn't indicate whether it was ASP.NET, WinForms, etc - this example is based on WinForms). Christian's suggestion above is in the right direction, but when I tried it out Clone()
didn't copy the values, and I couldn't see a way to get it to do that.
// Set up a List<T> to hold the indexes of the visible columns
List<int> visibleColumns = new List<int>();
foreach (DataGridViewColumn col in dgv1.Columns)
{
if (col.Visible)
{
dgv2.Columns.Add((DataGridViewColumn)col.Clone());
visibleColumns.Add(col.Index);
}
}
// Now add the data from the columns
// Set a counter for the current row index for the second DataGridView
int rowIndex = 0;
foreach (DataGridViewRow row in dgv1.Rows)
{
// Add a new row to the DataGridView
dgv2.Rows.Add();
// Loop through the visible columns
for (int i = 0; i < visibleColumns.Count; i++)
{
// Use the index of the for loop for the column in the target data grid
// Use the index value from the List<T> for the cell of the source target data grid
dgv2.Rows[rowIndex].Cells[i].Value = row.Cells[visibleColumns[i]].Value;
}
// Increment the rowIndex
rowIndex++;
}
I'll admit this is ugly and rather brute force, but I tested it and it worked. There may be better ways to do it, but this should at least help you some, I hope.
can't test it now..
foreach (DataGridViewColumn dgvCol in dgv1.Columns)
{
if (dvgCol.visible) dgv2.Columns.Add((DataGridViewColumn) dgvCol.Clone());
}
精彩评论