[英][C# DataGridView]How to make the datagridview receive the keydown event, not the cell control, after the cell edit
[英]Keydown event being swallowed/not actioned in DataGridView control
我根據文章DataGridView keydown事件開發的某些代碼有問題,但在C#中不起作用 。
我想允許用戶向Dataviewgrid控件添加一行,但是發現通過啟用AllowUserToAddRows
這導致在第一個字符鍵入新行的新單元格后立即顯示另一行。 這會使我的可憐的用戶感到困惑,因此,為了避免這種情況,我使用了上一篇文章中的代碼,在每次擊鍵時立即禁用AllowUserToAddRows
(盡管本來希望只在鍵入第一個字符之后才這樣做)。 但是,這似乎吞沒了第一個字符,即。 它不會傳遞給基類進行處理。 這是完整的代碼:
public sealed class XDataGridView : DataGridView
{
private bool _singleUpdateOnly = true;
public bool SingleUpdateOnly
{
get { return _singleUpdateOnly; }
set { _singleUpdateOnly = value; }
}
[Description("Disallows user adding rows as soon as a key is struck to ensure no blank row at bottom of grid")]
protected override bool ProcessCmdKey(ref System.Windows.Forms.Message msg, System.Windows.Forms.Keys keyData)
{
if (SingleUpdateOnly)
{
AllowUserToAddRows = false;
}
return base.ProcessCmdKey(ref msg, keyData);
}
}
為什么我輸入的第一個字符被吞下? 如何防止這種情況發生? 有沒有比我編寫的代碼更好的方法?
在這個論壇和其他論壇上,我對這個問題的回應很少。 這一定是一個非常棘手的問題,否則我只是對DataGridView控件期望過高。 經過數小時的反復試驗,我確定了不需要子類化的解決方案。 解決方案不完全是我想要的,即,一旦用戶開始在新添加的行中鍵入內容,就可以防止將另一行附加到網格底部,但這很接近。 我使用CellLeave
事件來關閉AllowUserToAddRows
。 當用戶按Tab或Enter鍵將數據輸入到第一個單元格時,這將有效地從網格中刪除新添加的行,而將用戶保留在網格中新添加的(最后)行的下一個單元格中(下面沒有空行) )。 不優雅,但至少大部分是實用的。 這是代碼:
private void uxContactEmailAddressesGrd_CellLeave(object sender, DataGridViewCellEventArgs e)
{
uxContactEmailAddressesGrd.AllowUserToAddRows = false;
}
也許有一天,其他人會遇到這個問題,找到比我更優雅的解決方案。 那簡直太好了。 確保將解決方案發布到此網站上,以供其他人使用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.