MyScenario,我有三行。我想要第一列的交换值。如何实现这一目标?
答案 0 :(得分:2)
function SwapField(DataTable table, string columnName, int firstRowIndex, int secondRowIndex)
{
int columnIndex = table.Columns.GetOrdinal(columnName);
if (columnIndex == -1)
{
// Throw exception
}
var secondRowField = dataTable.Rows[secondRowIndex][columnIndex];
dataTable.Rows[secondRowIndex][columnIndex] = dataTable.Rows[firstRowIndex][columnIndex];
dataTable.Rows[firstRowIndex][columnIndex] = secondRowField;
}
然后 SwapField(dataTable,'Column',0,1)交换前2行字段值
答案 1 :(得分:0)
除非你想要一些适用于任意行数的通用算法,否则我真的没有看到问题。在任何情况下,您都需要定义要在哪些行之间准确交换值;在两行之间交换非常简单,特别是如果您使用Framework的第4版,其中有两个针对DataRow的简洁扩展方法:Field和SetField。如果没有,您将需要获取每个DataRow的ItemArrays,交换数组中的值并将数组分配回其行。
答案 2 :(得分:0)
用于交换DataGridView的两行的示例代码
private void lblMoveDown_Click(object sender, EventArgs e)
{
moveDown();
}
private void lblMoveUp_Click(object sender, EventArgs e)
{
moveUp();
}
private void moveUp()
{
if (dgvTemplateListToManage.RowCount > 0)
{
if (dgvTemplateListToManage.SelectedRows.Count > 0)
{
DataTable dt=dgvTemplateListToManage.DataSource as DataTable;
int rowIndex = dgvTemplateListToManage.SelectedRows[0].Index;
if (rowIndex != 0)
{
DataRow row = dt.Rows[rowIndex];
DataRow drToDown= dt.Rows[rowIndex-1];
DataTable dtTemp = dt.Copy();
for (int i = 0; i < dt.Columns.Count; i++)
{
if (i != 0)
{
dtTemp.Rows[rowIndex][i] = drToDown[i].ToString();
}
}
for (int i = 0; i < dt.Columns.Count; i++)
{
if (i != 0)
{
dtTemp.Rows[rowIndex-1][i] = row[i].ToString();
}
}
dgvTemplateListToManage.DataSource = dtTemp;
}
}
}
}
private void moveDown()
{
DataTable dt = dgvTemplateListToManage.DataSource as DataTable;
int rowIndex = dgvTemplateListToManage.SelectedRows[0].Index;
int lastRowIndex = dgvTemplateListToManage.Rows.Count - 1;
if (lastRowIndex != rowIndex)
{
DataRow row = dt.Rows[rowIndex];
DataRow drToUp = dt.Rows[rowIndex + 1];
DataTable dtTemp = dt.Copy();
for (int i = 0; i < dt.Columns.Count; i++)
{
if (i != 0)
{
dtTemp.Rows[rowIndex][i] = drToUp[i].ToString();
}
}
for (int i = 0; i < dt.Columns.Count; i++)
{
if (i != 0)
{
dtTemp.Rows[rowIndex + 1][i] = row[i].ToString();
}
}
dgvTemplateListToManage.DataSource = dtTemp;
}
}
答案 3 :(得分:-3)
你需要写一些像
这样的东西`DataRow row = dt.Rows[index];
dt.RemoveAt(index);
dt.InsertAt(index -1);`