/*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;
}