C# dataGridView上下移动选中行
/*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;
}