大家好,今天我们来聊聊C#中一个实用的功能——如何在DataGridView中实现选中行的上下移动。
首先,我们需要明确的是,使用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(
