datagridview新增列在最后_DataGridView按回车换列,最后单元新增一行

这篇博客介绍了如何扩展Windows Forms DataGridView控件,使其在处理Enter键时更智能:单行新增、多行移动及特殊场景下移动到下一行。通过覆盖`ProcessDialogKey`和`ProcessRightKey`方法,实现定制化的键盘导航行为。
摘要由CSDN通过智能技术生成

using System;

using System.Collections.Generic;

using System.Text;

using System.Windows.Forms;

namespace WindowsFormsApplication

{

public class CustomDataGridView : DataGridView

{

protected override bool ProcessDialogKey(Keys keyData)

{

Keys key = (keyData & Keys.KeyCode);

if (key == Keys.Enter)

{

return this.ProcessRightKey(keyData);

}

return base.ProcessDialogKey(keyData);

}

public new bool ProcessRightKey(Keys keyData)

{

Keys key = (keyData & Keys.KeyCode);

if (key == Keys.Enter)

{

//第一种情况:只有一行,且当光标移到最后一列时,新增一行

if ((base.CurrentCell.ColumnIndex == (base.ColumnCount - 1)) && (base.RowCount ==1))

{

//新增一行

base.Rows.Add();

base.CurrentCell = base.Rows[base.RowCount - 1].Cells[0];

return true;

}

//第二种情况:有多行,且当光标移到最后一列时,移到下一行第一个单元,

if ((base.CurrentCell.ColumnIndex == (base.ColumnCount - 1)) &&(base.CurrentCell.RowIndex < (base.RowCount - 1)))

{

// base.Rows.Add();

base.CurrentCell = base.Rows[base.CurrentCell.RowIndex + 1].Cells[0];

return true;

}

//第三种情况:有多行,且当光标移到最后一行最后一列时,移到下一行第一个单元,新增一行

if ((base.CurrentCell.ColumnIndex == (base.ColumnCount - 1)) && (base.CurrentCell.RowIndex== base.RowCount -1))

{

//新增一行

base.Rows.Add();

base.CurrentCell = base.Rows[base.RowCount - 1].Cells[0];

return true;

}

return base.ProcessRightKey(keyData);

}

return base.ProcessRightKey(keyData);

}

protected override bool ProcessDataGridViewKey(KeyEventArgs e)

{

if (e.KeyCode == Keys.Enter)

{

return this.ProcessRightKey(e.KeyData);

}

//if (e.KeyCode == Keys.F4)

//{

//    return this.ProcessRightKey(e.KeyData);

//}

return base.ProcessDataGridViewKey(e);

}

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值