I made some progress but still there're some problems after sort by clicking on header grid collumn. I tried to reset the bindingSource1.Sort = ""; in the move rows function, and the row and now the row get moved but the position is wrong!! Here the code so you try by yourself..
public partial class Form1 : Form
{
DataTable dt;
DataSet ds = new DataSet();
public Form1()
{
InitializeComponent();
dt = new DataTable("table1");
dt.Columns.Add("Column1", typeof(int));
dt.Columns.Add("Column2", typeof(int));
dt.Columns.Add("Column3", typeof(int));
dt.Rows.Add(1, 0, 0);
dt.Rows.Add(2, 1, 1);
dt.Rows.Add(2, 0, 0);
dt.Rows.Add(3, 1, 1);
dt.Rows.Add(3, 0, 4);
dt.Rows.Add(3, 3, 4);
ds.Tables.Add(dt);
bindingSource1.DataSource = ds.Tables[0];
this.dataGridView1.DataSource = bindingSource1;
}
private void dataGridView1_Sorted(object sender, EventArgs e)
{
String sort = dataGridView1.SortedColumn.DataPropertyName;
if (dataGridView1.SortOrder == SortOrder.Descending)
{
sort = sort + " DESC";
}
bindingSource1.Sort = sort;
}
private void button1_Click(object sender, EventArgs e)
{
bindingSource1.Sort = "";
int index = this.bindingSource1.Position;
if (index > 0)
{
DataRow dr = (DataRow)this.ds.Tables["table1"].Rows[index];
DataRow newDr = this.ds.Tables["table1"].NewRow();
newDr.ItemArray = dr.ItemArray;
this.ds.Tables["table1"].Rows.RemoveAt(index);
this.ds.Tables["table1"].Rows.InsertAt(newDr, index - 1);
this.bindingSource1.Position = index - 1;
}
}
private void button2_Click(object sender, EventArgs e)
{
bindingSource1.Sort = "";
int index = this.bindingSource1.Position;
if (index < this.bindingSource1.Count)
{
DataRow dr = (DataRow)this.ds.Tables["table1"].Rows[index];
DataRow newDr = this.ds.Tables["table1"].NewRow();
newDr.ItemArray = dr.ItemArray;
this.ds.Tables["table1"].Rows.RemoveAt(index);
this.ds.Tables["table1"].Rows.InsertAt(newDr, index + 1);
this.bindingSource1.Position = index + 1;
}
}
}