Shadow89 Shadow89 - 2 months ago 18
C# Question

C# Visual Studios Inverting Rows in DataGridView

I am using a data grid, but the values do not display as I would like them to. My current code is below, how would I go about inverting the rows?

Invert Rows

string[] strOutput = strLine.Split('_', ',','=');

int totalRows = Convert.ToInt16(strOutput[4]);
int totalCols = Convert.ToInt16(strOutput[5]);
int itemIndex = 8;

for (int i = 0; i < totalCols; i++)
{ dataGridView1.Columns.Add("Col", "Col");
}
dataGridView1.Rows.Add(totalRows);
for (int i = 0; i < totalRows; i++)
{ for (int j = 0; j < totalCols; j++)
{ dataGridView1.Rows[i].Cells[j].Value = strOutput[itemIndex];
itemIndex += 2;
}
}
dataGridView1.Visible = true;
}


thanks for any help.

TaW TaW
Answer

To invert i.e. reverse DataGridViewRows you can use this:

void ReverseDGVRows(DataGridView dgv)
{
    List<DataGridViewRow> rows = new List<DataGridViewRow>();
    rows.AddRange(dgv.Rows.Cast<DataGridViewRow>());
    rows.Reverse();
    dgv.Rows.Clear();
    dgv.Rows.AddRange(rows.ToArray());
}

If you only need to do it once you could instead either:

  • loop over the lnes of the source file in reverse
  • or instead of Adding the rows (to the end) Insert at the top:

dtnew.Rows.Insert(0, currentDataRowView.Row);