繁体   English   中英

如何反转DataGridView中的行

[英]How to reverse rows in a DataGridView

我正在使用数据网格,但值不会像我希望的那样显示。 我目前的代码如下,我将如何反转行?

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;

反转行

要反转即反向DataGridViewRows您可以使用:

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

如果你只需要做一次,你可以改为:

  • 反过来循环遍历源文件的行
  • 或者代替Adding行(到最后)在顶部Insert

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

反转行:

“DataGridView.Rows”.-将为您提供“DataGridViewRowCollection”

以相反的顺序迭代集合并创建一个新的数据表。 (用于从最大尺寸到零的循环)

将新数据表分配给datagridview源。

这个粗略的代码写在记事本中为您的想法。 我现在没有IDE。

DataGridViewRowCollection dgRowColllection = dataGridView1.Rows;
DataTable dtnew = new DataTable();
for(i = dataGridView1.RowCount; i  < 1 ; i--)
{
DataRowView currentDataRowView = dgRowColllection[i].Row;

dtnew.Rows.Add(currentDataRowView.Row);

}

dataGridView1.source = dtnew;

无法对Pavan的答案发表评论,因为我没有50个声望,但是你得到的错误是因为循环应该是这样的:

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;
       }
       DataGridViewRowCollection dgRowColllection = dataGridView1.Rows;
       DataTable dtnew = new DataTable();
       for (i = dataGridView1.Items.Count; i < 1; i--)
       {
            DataRowView currentDataRowView = dgRowColllection[i].Row;
            dtnew.Rows.Add(currentDataRowView.Row);
       }
       dataGridView1.DataSource = dtnew;
   }    
   dataGridView1.Visible = true;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM