I recently posted a question on how to populate a 2 dimensional array with data from 7 datagridviews, each with 7 rows x 5 columns. Enigmativity supplied me with a piece of code that worked great, many thanks.
public string[,] myGridData = new string[50, 5];
//49 data rows, last row (50) contains version number
var dgvs = new[] { dgv6, dgv5, dgv4, dgv3, dgv2, dgv1, dgv0, };
for (var i = 0; i < dgvs.Length; i++)
{
for (int rows = 0; rows < 7; rows++)
{
for (int col = 0; col < 5; col++)
{
myGridData[rows + i * 7, col] = dgvs[i].Rows[rows].Cells[col].Value.ToString();
}
}
}
I now need a way to reverse the procedure and populate the 7 datagridviews from the original array.
I know how to populate a single datagridview from a 2d array, but not sure how to populate all 7 grids. The code I have been using to fill 1 grid is:
//Populate Single DataViewGrid
var rowCount = myGridData.GetLength(0);
var rowLength = myGridData.GetLength(1);
dgv1.ColumnCount = 5;
for (int rowIndex = 0; rowIndex < rowCount - 1; ++rowIndex)
{
var row = new DataGridViewRow();
for (int columnIndex = 0; columnIndex < rowLength; ++columnIndex)
{
row.Cells.Add(new DataGridViewTextBoxCell()
{
Value = myGridData[rowIndex, columnIndex]
});
}
dgv1.Rows.Add(row);
}
Thanks in advance.
Just like populating the 2d array, you need to iterate through the 7 DataGridView
controls. Nesting your code within that loop, you then change how far your inner loop iterates. Instead of iterating rowCount - 1
, filling one DataGridView
with all 49 rows, you only iterate over the next 7 rows. By moving rowIndex
outside of the outermost loop, it will "remember" the next index as you progress through each view.
var rowCount = myGridData.GetLength(0);
var rowLength = myGridData.GetLength(1);
int rowIndex = 0;
var dgvs = new[] { dgv6, dgv5, dgv4, dgv3, dgv2, dgv1, dgv0, };
for (int i = 0; i < dgvs.Length; i++)
{
var dgv = dgvs[i];
dgv.ColumnCount = 5;
for (int taken = 0; taken < 7; ++taken, ++rowIndex)
{
var row = new DataGridViewRow();
for (int columnIndex = 0; columnIndex < rowLength; ++columnIndex)
{
row.Cells.Add(new DataGridViewTextBoxCell()
{
Value = myGridData[rowIndex, columnIndex]
});
}
dgv.Rows.Add(row);
}
}
If it makes you feel better, you can modify the inner loop to:
for (int taken = 0; taken < 7 && rowIndex < rowCount - 1; ++taken, ++rowIndex)
But honestly it will still execute the same and is creating an additional logic check for each iteration.
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.