Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Invert Rows

like image 247
Shadow89 Avatar asked Oct 21 '25 21:10

Shadow89


1 Answers

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 lines 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);
like image 115
TaW Avatar answered Oct 23 '25 12:10

TaW



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!