Hi,
Friedhelm Drecktrah said:
Hi,
I have a dataGridView databinded to a dataSet. The Rows are in a specific
order and I want to swap the selected row with the row below it. I have a
RowNum (int) Field in the database. How can I do this?
If RowNum is also a column inside a DataTable of dataSet and that column
specifies the order then you could start by adding a BindingSource between
the DataSet and DataGridView if you haven't already (from code or with the
designer):
bindingSource1.DataSource = dataSet;
bindingSource1.DataMember = "tablename";
bindingSource1.Sort = "RowNum";
dataGridView.DataSource = bindingSource1;
dataGridView.DataMember = "";
Then you can use this code:
public void SwapRows()
{
DataView dv = (DataView)bindingSource1.List;
if (bindingSource1.Position + 1 < dv.Count)
{
DataRow dr1 = dv[bindingSource1.Position].Row;
DataRow dr2 = dv[bindingSource1.Position + 1].Row;
int rowNum1 = (int)dr1["RowNum"];
int rowNum2 = (int)dr2["RowNum"];
dr1["RowNum"] = -1; // avoid pos. constraint errors
dr2["RowNum"] = rowNum1;
dr1["RowNum"] = rowNum2;
}
}
HTH,
Greetings