首页 > 代码库 > GridView Tab/Enter键插入新行

GridView Tab/Enter键插入新行

/// <summary>
/// GridView添加新行
/// </summary>
public sealed class GridNewRowHelper
{

     private readonly GridView _View;
     /// <summary>
     /// 构造函数:按键为GridView添加新行(Tab/Enter)
     /// </summary>
     /// <param name="view">目标GridView</param>
     public GridNewRowHelper(GridView view)
     {
         _View = view;
         _View.HiddenEditor += _View_HiddenEditor;
         view.GridControl.EditorKeyDown += GridControl_EditorKeyDown;
         view.GridControl.KeyDown += new KeyEventHandler(GridControl_KeyDown);
     }

     void _View_HiddenEditor(object sender, EventArgs e)
     {
     }

     void GridControl_KeyDown(object sender, KeyEventArgs e)
     {
         e.Handled = OnKeyDown(e.KeyCode, e.Modifiers);
     }

     void GridControl_EditorKeyDown(object sender, KeyEventArgs e)
     {
         e.Handled = OnKeyDown(e.KeyCode, e.Modifiers);
     }
     private bool OnKeyDown(Keys keyCode, Keys modifiers)
     {
         if (modifiers == Keys.None && (keyCode == Keys.Enter || keyCode == Keys.Tab))
         {
             return CheckAddNewRow();
         }
         return false;
     }

     private bool CheckAddNewRow()
     {
         if (_View.FocusedColumn.VisibleIndex == _View.VisibleColumns.Count - 1)
         {
             if (_View.IsNewItemRow(_View.FocusedRowHandle))
             {
                 _View.PostEditor();
                 _View.UpdateCurrentRow();
             }
             if (_View.IsLastRow)
                 return AddNewRow();
         }
         return false;
     }

     private bool AddNewRow()
     {
         _View.AddNewRow();
         _View.FocusedColumn = _View.VisibleColumns[0];
         return true;
     }
}

使用方法:

GridNewRowHelper newRowView=new GridNewRowHelper (targetView);

GridView Tab/Enter键插入新行