title: How to move datagridview rows up or down based on a button click
body: <p>I have DataGridView which is bounded with a datatable. I fill this datatable from database. I have 2 buttons right next to the datagridview, Up and Down. the rows should move up and down based on whichever button i click. I understand there are many answers for the similar issues but they work if your gridview isnt bounded. I also have a sequence column which has numbers from 0 onwards. When the rows move up or down, the sequence should be fixed as well. For example, if i move row[12] up, the sequence of row[12] should update to row[11] and row[11] should move down and row[11] sequence becomes row[12]. (I'm sorry if this is confusing). I also have 2 event functions attached to up and down buttons as well.</p>
  
  <p><strong>Edit</strong>: The main goal of this gridview is that user can add new rows as well. So, along with the above information, if there are 5 rows with sequence 1 to 5, and the user adds another row with sequence 2. I can sort the rows but how do I make the origninal rows with sequence 2,3,4,5 shift down and change their sequence to 3,4,5,6?</p>
  
  <pre><code>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 &lt;= 0 || newSequence &gt; 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 &amp;&amp; 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);
      }
  </code></pre>
  
  <p>There are definitely some loopholes in my explanation so please be kind. I will do my best to explain any confusions, if need be.</p>