C# dataGridView上下移動選中行

來源:互聯網
上載者:User

/*DataGridView 實現行[Row]的上下移動,我這裡用到了SelectedRows[0],而沒用CurrentRow是有原因的
   主要是這兩段代碼:
   dataGridView1.Rows[rowIndex - 1].Selected = true;
   dataGridView1.Rows[rowIndex].Selected = false;
   這兩行代碼大家因該都能看懂,移上去的哪行選中狀態,移下去的的取消選中狀態.
   如果我用dataGridView1.CurrentRow.Cell[0].Value 他取得的值仍然是rowIndex索引行的值
    要使用SelectedRows[0] ,就必須設定這個屬性:dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;

   實現原理:就是上下兩行,把儲存格中的值進行交換...呵呵表面上看去是向上,下移動了

   不知道大家還有什麼好的選中方法沒...請多多指教 

*/

    private void Form3_Load(object sender, EventArgs e)
    {
      //........得到DataTable的代碼省略....
      dataGridView1.DataSource = dt;
    }

    private void button1_Click(object sender, EventArgs e)  //向上移動
    {
      int rowIndex = dataGridView1.SelectedRows[0].Index;  //得到當前選中行的索引

      if(rowIndex == 0)
      {
        MessageBox.Show("已經是第一行了!");
        return;
      }

      List<string> list = new List<string>();
      for (int i = 0; i < dataGridView1.Columns.Count; i++)
      {
        list.Add(dataGridView1.SelectedRows[0].Cells[i].Value.ToString());   //把當前選中行的資料存入list數組中
      }

      for (int j = 0; j < dataGridView1.Columns.Count; j++)
      {
          dataGridView1.Rows[rowIndex].Cells[j].Value = dataGridView1.Rows[rowIndex - 1].Cells[j].Value;
          dataGridView1.Rows[rowIndex - 1].Cells[j].Value = list[j].ToString();
      }
      dataGridView1.Rows[rowIndex - 1].Selected = true;
      dataGridView1.Rows[rowIndex].Selected = false;
    }

    private void button2_Click(object sender, EventArgs e)  //向下移動
    {
      int rowIndex = dataGridView1.SelectedRows[0].Index;  //得到當前選中行的索引

      if (rowIndex == dataGridView1.Rows.Count -1)
      {
        MessageBox.Show("已經是最後一行了!");
        return;
      }

      List<string> list = new List<string>();
      for (int i = 0; i < dataGridView1.Columns.Count; i++)
      {
        list.Add(dataGridView1.SelectedRows[0].Cells[i].Value.ToString());   //把當前選中行的資料存入list數組中
      }

      for (int j = 0; j < dataGridView1.Columns.Count; j++)
      {
        dataGridView1.Rows[rowIndex].Cells[j].Value = dataGridView1.Rows[rowIndex + 1].Cells[j].Value;
        dataGridView1.Rows[rowIndex + 1].Cells[j].Value = list[j].ToString();
      }
      dataGridView1.Rows[rowIndex + 1].Selected = true;
      dataGridView1.Rows[rowIndex].Selected = false;
    }

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.