简体   繁体   English

在C#中的datagridview中交换行

[英]swap rows in datagridview in c#


i have a datagridview which is not related with dataTable. 我有一个与dataTable不相关的datagridview。
and i want to swap for example 1st and 10th rows in datagridview. 我想交换例如datagridview中的第一行和第十行。
i use this code for it 我为此使用此代码

int row_1 = 1;
int row_10 = 10;
for(int i=0;i<grid.ColumnCount;i++)
{
  string temp = grid.Rows[row_1].Cells[i].Value.ToString();
  grid.Rows[row_1].Cells[i].Value = grid.Rows[row_10].Cells[i].Value.ToString();
  grid.Rows[row_10].Cells[i].Value = temp;
}

but i want to know is there any simple way to do this?? 但我想知道有没有简单的方法可以做到这一点?

var r10 = grid.Rows[9];
var r1 = grid.Rows[0];
grid.Rows.Remove(r1);
grid.Rows.Remove(r10);
grid.Rows.Insert(0, r10);
grid.Rows.Insert(9, r1);

HI, 嗨,
Have you tried: 你有没有尝试过:

DataGridViewRow temp =grid.Rows[row_1];
grid.Rows[row_1] = grid.Rows[row_10];
grid.Rows[row_10] = temp;

I wanted to comment on this. 我想对此发表评论。

While it -may- have been possible to do a straight swap in C# before, like smoore/Gabriels- 尽管以前可以用C#进行直接交换,例如smoore / Gabriels-

DataGridViewRow temp = grid.Rows[row_1].Clone();
grid.Rows[row_1] = grid.Rows[row_10].Clone();
grid.Rows[row_10] = temp;

This is no longer possible, as grid.Rows[index] is read only. 这不再可能,因为grid.Rows [index]是只读的。

Instead, use DarkSquirrels method of saving the two rows, removing the rows, and re-inserting them swapped. 而是,使用DarkSquirrels方法保存两行,删除这些行,然后重新插入交换它们。

If somebody knows a better method (as this is like a 6 line method by iteslf without the logic to find the other value) please do comment! 如果有人知道更好的方法(因为这就像iteslf的6行方法,而没有找到其他值的逻辑),请发表评论!

Try: 尝试:

DataGridViewRow temp = grid.Rows[row_1].Clone();
grid.Rows[row_1] = grid.Rows[row_10].Clone();
grid.Rows[row_10] = temp;

Just as addition: 就像另外:

if you need interchange more often, put the method above you prefer most in its own class and call the method (eg Interchange()) 如果您需要更频繁地交换,请将方法放在您最喜欢的方法之上,放在其自己的类中,然后调用该方法(例如Interchange())

This method works fine: 此方法工作正常:

private static void SwapRows(DataGridView grid, int row1, int row2)
{
  if (row1 != row2 && row1 >= 0 && row2 >= 0 && row1 < grid.RowCount && row2 < grid.RowCount)  
  {
    var rows = grid.Rows.Cast<DataGridViewRow>().ToArray();
    var temp = rows[row1];
    rows[row1] = rows[row2];
    rows[row2] = temp;
    grid.Rows.Clear();
    grid.Rows.AddRange(rows);
  }
}

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

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