neděle 9. června 2013

DevExpress BarEditItem Closing-Editor at runtime to obtain entered value

I think everybody already faced problem with value in editor by DevExpress WinForms application. Usually it happens when we want to use value immediately the ENTER was pressed in EditorCell. The first action we have to do is CloseEditor, to force editor store the entered value.

The problem comes when the editor is placed into toolbar as the BarEditItem.

The BarEditItem has no CloseEditor method implemented. After short investigation I learned, that current editor is not runned under BarEditItem but by the link to BarEditItem. The BarEditItem has collection of Links, which reference all instances of this BarEditItem displayed in the menu. So if you want close the editor, you must find the correct one by Links array.

My final solution is Extension method to BarEditItem, which closes all possible linked editors (yup, little hack, but helpful).

Here is my code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
 
namespace DevExpress.XtraBars
{
    public static class DevExpressWinFormBarEditItemExtension
    {
        /// <summary>
        /// Extension Method. Closes all editors joined over links (BarItemLink) to BarEditItem and and close them.
        /// </summary>
        /// <param name="item"></param>
        public static void CloseAllEditors(this BarEditItem item) {
            foreach (BarEditItemLink link in item.Links.OfType<BarEditItemLink>()) { link.CloseEditor(); } 
        }
    }
}

... and here is usage in action:
        private void reibeSupOrderNr_KeyDown(object senderKeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                beiSupOrderNr.CloseAllEditors();
                addItemAccordingToolbatText();
            }
        }