【发布时间】:2019-07-23 16:17:10
【问题描述】:
我有与数据表绑定的 DataGridView。我从数据库中填充这个数据表。我在datagridview旁边有2个按钮,向上和向下。行应根据我单击的按钮上下移动。我知道类似问题有很多答案,但如果您的 gridview 没有界限,它们会起作用。我还有一个序列列,其中的数字从 0 开始。当行向上或向下移动时,顺序也应该是固定的。例如,如果我将 row[12] 向上移动,则 row[12] 的序列应该更新为 row[11] 并且 row[11] 应该向下移动并且 row[11] 序列变为 row[12]。 (如果这令人困惑,我很抱歉)。我还为向上和向下按钮附加了 2 个事件函数。
编辑:此网格视图的主要目标是用户也可以添加新行。因此,连同上述信息,如果有 5 行序列为 1 到 5,并且用户添加了序列为 2 的另一行。我可以对行进行排序,但我如何制作序列为 2、3、4 的原始行, 5 下移并改变它们的顺序为 3,4,5,6?
private void moveRow(int position)
{
DataRow selectedDataRow = null;
DataRow newDataRow = null;
int sequence = -1;
int newSequence = -1;
DataGridViewRow selectedRow = dataGridView.SelectedRows[0];
sequence = (int)selectedRow.Cells[sequenceDataGridViewTextBoxColumn.Index].Value;
newSequence = sequence + position;
if (newSequence <= 0 || newSequence > dataGridView.Rows.Count)
{
return;
}
//below code doesnt work at all maybe cuz it isnt right
//How do i select the current row and the row at the new sequence?????
if (selectedDataRow != null && newDataRow != null)
{//below i try to assign sequences to the rows
selectedDataRow["Sequence"] = newSequence;
newDataRow["Sequence"] = sequence;
}
dataGridViewRed.Sort(dataGridViewRed.Columns[buildSequenceDataGridViewTextBoxColumn.Index], ListSortDirection.Ascending);// i sort it again based on sequence
dataGridViewRed.CurrentCell = dataGridViewRed.Rows[selectedRow.Index + position].Cells[buildSequenceDataGridViewTextBoxColumn.Index];//highlight the current selected cell
//below functions are the events attached to the buttons for up and down
private void UpBtn_Click(object sender, EventArgs e)
{
moveRow(-1);
}
private void DownBtn_Click(object sender, EventArgs e)
{
moveRow(+1);
}
我的解释肯定有一些漏洞,所以请多多指教。如果需要,我会尽力解释任何混淆。
【问题讨论】:
-
为什么不按序列值排序并保持它而不是尝试管理 bound 控件中的行?
-
让我编辑我的问题。我忘记了一个重点。对不起。
-
当他们添加时,遍历数据源并更新 2 或以上的 ID。如果您使用正确的集合类型,DGV 将自行(重新)排序。您不应该尝试在绑定控件中管理 DGV 行
标签: c# visual-studio-2015 datagridview