Shadow89 Shadow89 - 1 year ago 118
C# Question

How to reverse rows in a 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?

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");
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;

Invert Rows

Answer Source

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

void ReverseDGVRows(DataGridView dgv)
    List<DataGridViewRow> rows = new List<DataGridViewRow>();

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);