I created Scintilla Popup for textbox to show autocomplete :
this.hWnd = CreateWindowEx(
0, "Scintilla", "",
WS_CHILD | WS_VISIBLE | WS_TABSTOP | WS_CLIPCHILDREN | 0x00002000,
x, y, textbox1.ClientSize.Width, textbox1.ClientSize.Height, textbox1.Handle, (IntPtr)0, (IntPtr)0, (IntPtr)0);
and in custom textbox, i overriden WndProc :
protected override void WndProc(ref Message m)
{
}
I build project in x86, and each time i call "SendMessage", the autocomplete showed on textbox and WndProc called. But when i build project in x64, only autocomplete showed and WndProc not called. Please, help me ??
Thanks.
EDIT: Added code below, previously posted by OP as an answer
#o_weisman, this is my custom textbox :
public partial class ScintillaControl : TextBox
{
ScintillaWrapper sw = null;
public ScintillaWrapper Scintilla
{
get { return this.sw; }
}
LanguageType languageType = LanguageType.CS;
public LanguageType LanguageType
{
get { return languageType; }
set { languageType = value; }
}
bool useBuiltInPopupMenu = true;
public bool UseBuiltInPopupMenu
{
get { return useBuiltInPopupMenu; }
set { useBuiltInPopupMenu = value; }
}
bool _notModified = false;
public bool NotModified
{
get { return _notModified; }
set { _notModified = value; }
}
public ScintillaControl()
{
this.Multiline = true;
this.AcceptsTab = true;
// this.ShortcutsEnabled = true;
}
protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
const int WM_KEYDOWN = 0x100;
var keyCode = (Keys)(msg.WParam.ToInt32() &
Convert.ToInt32(Keys.KeyCode));
if ((msg.Msg == WM_KEYDOWN && keyCode == Keys.A)
&& (ModifierKeys == Keys.Control)
)
{
this.SelectAll();
return true;
}
return base.ProcessCmdKey(ref msg, keyData);
}
public new bool Enabled
{
get { return base.Enabled; }
set
{
base.Enabled = value;
Color bkColor = (value ? Color.White : System.Drawing.SystemColors.ControlLight);
if (this.sw != null)
this.sw.SetWindowBackground(bkColor);
}
}
//[DllImport("User32.dll")]
//private static extern int GetAsyncKeyState(int vKey);
private bool DetectCtrlPressed()
{
Keyboard kb = new Keyboard();
return kb.CtrlKeyDown;
//int detectCtrlPressed = GetAsyncKeyState(0x11);
//return (detectCtrlPressed == 32768 || detectCtrlPressed == -32767);
}
private bool DetectCtrlShiftPressed()
{
Keyboard kb = new Keyboard();
return kb.CtrlKeyDown && kb.ShiftKeyDown;
}
private bool DetectShiftPressed()
{
Keyboard kb = new Keyboard();
return kb.ShiftKeyDown;
}
protected override void OnCreateControl()
{
base.OnCreateControl();
CreateScintillaControl();
}
public void CreateScintillaControl()
{
if (this.sw != null)
return;
try
{
this.sw = new ScintillaWrapper();
this.sw.MapForm = this.mapForm;
this.sw.ParentControl = this;
this.sw._CreateWindow(0, 0, this.ClientSize.Width, this.ClientSize.Height, this, languageType);
this.sw._DisableBuiltInPopupMenu(this.useBuiltInPopupMenu);
//Trace.Listeners.Add(new TextWriterTraceListener("C:\\trace.txt"));
}
catch (Exception ex)
{
MessageBox.Show("error while creating scintilla wrapper, ex: " + ex.ToString());
}
}
protected override void OnSizeChanged(EventArgs e)
{
base.OnSizeChanged(e);
if (this.sw != null)
this.sw._ChangeSize(new Point(0, 0), new Size(this.ClientSize.Width, this.ClientSize.Height));
}
public delegate void ScintillaDoubleClick(int lineNumber, string content);
public event ScintillaDoubleClick OnScintillaDoubleClick = null;
private void DoOnScintillaDoubleClick(int lineNumber, string content)
{
if (this.OnScintillaDoubleClick != null)
this.OnScintillaDoubleClick(lineNumber, content);
}
public delegate void TrackPopupMenu(Point p);
public event TrackPopupMenu OnTrackPopupMenu = null;
private void DoOnTrackPopupMenu(Point p)
{
if (this.OnTrackPopupMenu != null)
this.OnTrackPopupMenu(p);
}
public delegate void CodeChanged(ScintillaControl control);
public event CodeChanged OnCodeChanged = null;
private void DoOnCodeChanged(ScintillaControl control)
{
if (this.OnCodeChanged != null)
this.OnCodeChanged(control);
}
public delegate void SelectionChanged(bool isChanged);
public event SelectionChanged OnSelectionChanged = null;
private void DoOnSelectionChanged(bool isChanged)
{
if (this.OnSelectionChanged != null)
this.OnSelectionChanged(isChanged);
}
public delegate void ModifyCode();
public event ModifyCode OnModifyCode = null;
private void DoOnModifyCode()
{
this.sw.ReDrawLineNumberPanel();
if (this.OnModifyCode != null)
this.OnModifyCode();
}
public delegate void UIChangedDelegate();
public event UIChangedDelegate OnUIChanged = null;
protected override void OnGotFocus(EventArgs e)
{
base.OnGotFocus(e);
this.sw._SetFocus();
}
private const int WM_PASTE = 0x0302;
protected override void WndProc(ref Message m)
{
if (m.Msg == ScintillaWrapper.SCK_DELETE)
{
this.DoOnCodeChanged(this);
}
else if (m.Msg == 0x0111 /*WM_COMMAND*/ && this.sw != null)
{
if (m.LParam == this.sw._HWnd)
{
int value = m.WParam.ToInt32();
if ((value >> 16) == 512)
{
this.Select();
//this.sw._SetFocus();
}
}
}
else if (m.Msg == 0x007B /*WM_CONTEXTMENU*/ && this.useBuiltInPopupMenu == false)
{
int value = m.LParam.ToInt32();
// tach value lam low word va high word
int lowWord = value & 0x0000FFFF;
int highWord = value >> 16;
Point p = new Point(lowWord, highWord);
this.Select();
//this.sw._SetFocus();
this.DoOnTrackPopupMenu(p);
return;
}
else if (m.Msg == 0x004E /*WM_NOTIFY*/ && this.sw != null)
{
this.ProcessNotify(m);
}
base.WndProc(ref m);
}
CalltipInfo _currentCallTip = null;
bool _hasSelect = false;
bool _hasSelect2 = false;
SCNotification tmpNotify;
private void ProcessNotify(Message m)
{
bool is64bit = Util.Utility.OtherFunction.IsOS64bit;
SCNotification notify;
uint code = 0;
if (is64bit)
{
IntPtr pDevicePathName = new IntPtr(m.LParam.ToInt64() + IntPtr.Size);
notify = (SCNotification)Marshal.PtrToStructure(pDevicePathName, typeof(SCNotification));
code = notify.idFrom;
}
else
{
notify = (SCNotification)Marshal.PtrToStructure(m.LParam, typeof(SCNotification));
code = notify.code;
}
//if (notify.hwndFrom != this.sw._HWnd)
// return;
switch (code)//(notify.code)
{
case ScintillaWrapper.SCN_MARGINCLICK:
if (notify.margin == ScintillaWrapper.MARGIN_SCRIPT_FOLD_INDEX) this.Scintilla._Fold(notify.position);
else if (notify.margin == 2)
{
this.Scintilla._ToggleBreakPoint(notify.position);
}
break;
case ScintillaWrapper.SCN_CHARADDED:
if (this.sw.GetReadOnly()) break;
if (this.sw._CharAdd(notify.ch, this.DetectCtrlPressed(), this.DetectShiftPressed()))
break;
this.DoOnModifyCode();
this.OnTextChanged(new EventArgs());
break;
case ScintillaWrapper.SCN_AUTOCSELECTION:
_hasSelect = true;
// string s = Marshal.PtrToStringAnsi(notify.text);
// this.Scintilla._AutoCompleteSelected(notify.lParam.ToInt32(), s);
break;
case ScintillaWrapper.SCN_CALLTIPCLICK:
this.Scintilla._CalltipClicked(notify.position);
break;
case ScintillaWrapper.SCN_DOUBLECLICK:
int lineNumber = this.sw.GetCurrentLine();
string content = this.sw.GetLineContent(lineNumber);
this.DoOnScintillaDoubleClick(lineNumber, content);
break;
case ScintillaWrapper.SCN_SAVEPOINTLEFT:
this.DoOnCodeChanged(this);
break;
case ScintillaWrapper.SCN_DWELLSTART:
this.sw._MouseOver(notify.position);
break;
case ScintillaWrapper.SCN_DWELLEND:
this.sw._MouseOut();
break;
case ScintillaWrapper.SCN_UPDATEUI:
this.sw._CursorChanged();
if (this.sw.GetText() != "")
{
this.getCurrentColPos();
}
if (this.OnUIChanged != null)
OnUIChanged();
//this.DoOnModifyCode();
break;
case ScintillaWrapper.SCN_MODIFIED:
if (notify.modificationType == 2064 && notify.length == 1 && _notModified == false)
{
this.DoOnModifyCode();
this.OnTextChanged(new EventArgs());
}
else if ((notify.modificationType == 1040 || notify.modificationType == 2064) && !_notModified)
{
this.DoOnModifyCode();
}
//DVC 2/4/10
if (!ReferencesHolder.IsSearching)
{
if (this.Scintilla._GetBit(1, notify.modificationType))//Delete text event
{
this.Scintilla._CheckBreakPoint(notify.position);
}
}
//End
if (_hasSelect && ((notify.modificationType & ScintillaWrapper.SC_MOD_INSERTTEXT) != 0))
{
_hasSelect2 = true;
_hasSelect = false;
}
break;
case ScintillaWrapper.SCN_SELECT_AC_ITEM:
string s = Marshal.PtrToStringAnsi(notify.text);
_currentCallTip = this.sw.ShowToolTip(new Point(notify.x, notify.y), notify.position, notify.margin, notify.message, s);
tmpNotify = notify;
break;
case ScintillaWrapper.SCN_CLOSE_AC_LIST:
this.sw.HideToolTip();
break;
//case ScintillaWrapper.SCN_PAINTED:
// break;
case ScintillaWrapper.SCK_DELETE:
this.DoOnModifyCode();
break;
default:
if (_hasSelect2)
{
AddParenthesisIfNeeded();
_hasSelect2 = false;
sw.InsertText(" ");
sw.AutoCompleteProcess.InitAutoComplete(32, sw.GetCurrentPos(), sw.GetText(), false, true);
//string s1 = Marshal.PtrToStringAnsi(tmpNotify.text);
//this.sw.ShowToolTip(new Point(tmpNotify.x, tmpNotify.y), tmpNotify.position, tmpNotify.margin, tmpNotify.message, s1);
}
bool isChanged = this.sw.HasSelection();
this.DoOnSelectionChanged(isChanged);
//this.DoOnModifyCode();
break;
}
}
public void getCurrentColPos()
{
Control parent = this.Parent;
while (!(parent == null) && !(parent.Name == "Check Output"))
{
parent = parent.Parent;
}
if (parent != null)
{
var lengthOfAlllineBefore = 0;
var currentPos = 0;
if (this.sw.GetCurrentLine() > 0)
{
for (int i = 0; i < this.sw.GetCurrentLine(); i++)
{
lengthOfAlllineBefore += this.sw.GetLineContent(i).Length;
}
currentPos = this.sw.GetCurrentPos() - lengthOfAlllineBefore;
}
else
{
currentPos = this.sw.GetCurrentPos();
}
if (parent.Controls["panel2"] != null)
{
parent.Controls["panel2"].Controls["lblCurrentColumnPosition"].Text =
string.Format("Col:{0}", currentPos);
}
}
// this.sw.get
}
private void AddParenthesisIfNeeded()
{
try
{
string text = sw.GetText();
sw.AutoCompleteProcess.DocumentString = text;
_currentCallTip = sw.AutoCompleteProcess.FindCalltipVariable(sw.GetCurrentPos() - 1, text, 0);
if (_currentCallTip == null || _currentCallTip.IsProperty)
{
return;
}
sw.InsertText("()");
sw.SetCurrentPos(sw.GetCurrentPos() - 1);
sw.ClearSelection();
_currentCallTip = null;
}
catch { }
}
public void SetSavePoint()
{
if (this.sw != null)
this.sw._SetSavePoint();
}
public void SetReadOnly(bool readOnly)
{
this.Scintilla.SetReadOnly(readOnly);
}
public void ToggleBreakPoint()
{
this.Scintilla._ToggleBreakPoint();
}
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
if (this.sw != null)
this.sw.Dispose();
this.OnTrackPopupMenu = null;
this.OnCodeChanged = null;
this.OnSelectionChanged = null;
this.OnTrackPopupMenu = null;
}
private void InitializeComponent()
{
this.SuspendLayout();
//
// ScintillaControl
//
this.Multiline = true;
this.ResumeLayout(false);
}
}
Related
We have a Till Software which also works with restaurants built on .NET (C#) and Firebird DB. We are having a strange problem recently, the items in an order are duplicating themselves when we go back to the order.
Strangely it's not the case always. It's happening only sometimes. I tried to figure out under what conditions it's happening but it's so random that it doesn't happen for a couple of days and then start duplicating items for the next two days.
The software is so huge that I don't know what code snippets to even post. As it's not happening always and is random I guess it doesn't have to do with the code but with Firebird DB maybe.
The other thing I wanted to mention is that we had a Firebird DB built on a 32-bit machine and when we tried to put it on a 64 - bit machine it didn't work. So, we had to take a backup of the DB on a 32-bit machine and restore it on a 64-bit machine and it worked with the software. I'm thinking does that have something to do with it? but we have another user on 32-bit with no conversion and it's the same case for him as well.
I'll really appreciate any help or guidance on this.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;
using Till_Library.Till_Controls;
using Till_Library.Till_Interfaces;
using Till_Library.Till_Presenters;
using Till_Library.Till_Types;
namespace Till_Library.Till_Views
{
public partial class viewOrderItems : UserControl
{
private IOrder mIOrder;
private PresenterOrder mPresenterOrder;
private readonly List<OrderGridItemRow> mOrderItemRowList;
private OrderGridItemRow mCurrentItemRow;
private readonly Color paidBckcolour = Color.GreenYellow;
private decimal mTillMode;
private readonly int ITEM_GRID_ROWS;
private int mItemGridStartIdx;
private int mItemGridEndIdx;
private int mLastDisplayedRowIdx;
private int mLastItemCount;
private bool mSplitMode;
public bool mIsRefund;
private RestTable mCurrentTable;
public delegate void TillCustDetailsClickedHandler();
public delegate void TillOrderItemPhoneClickedHandler();
public delegate void TillOrderTableSelectionClickedHandler();
public delegate void TillOrderTableCoverClickedHandler();
public delegate void TillOrderPriceClickedHandler(Point KeyPadLocation);
public delegate void TillOrderQuantityClickedHandler(Point KeyPadLocation);
public delegate void TillOrderItemClickedHandler(bool Option);
public delegate void TillOrderCheckBoxClickedHandler(OrderItemDetails pOrderItemRow);
public viewOrderItems(bool isRefund = false)
{
InitializeComponent();
ITEM_GRID_ROWS = 11;
mItemGridStartIdx = 0;
mItemGridEndIdx = ITEM_GRID_ROWS;
mIsRefund = isRefund;
int CurY = 0;
mIOrder = new IOrder();
mOrderItemRowList = new List<OrderGridItemRow>();
for (int i = 1; i <= ITEM_GRID_ROWS; i++)
{
CreateOrderItemRowControl(i, CurY);
CurY += 36;
}
}
private void CreateOrderItemRowControl(int pIdx, int pCurY)
{
string ItemRowName = "orderGridItemRow" + pIdx;
mOrderItemRowList.Add(new OrderGridItemRow(pIdx));
mOrderItemRowList[pIdx - 1].Name = ItemRowName;
mOrderItemRowList[pIdx - 1].Location = new Point(4, pCurY);
mOrderItemRowList[pIdx - 1].Parent = panItems;
//OrderItemRowList[pIdx - 1].Parent = panel2;
mOrderItemRowList[pIdx - 1].OrderItemClicked += TillOrderItemClicked;
mOrderItemRowList[pIdx - 1].OrderItemPriceClicked += TillOrderItemPriceClicked;
mOrderItemRowList[pIdx - 1].OrderItemPriceLeft += TillOrderItemPriceLeft;
mOrderItemRowList[pIdx - 1].OrderItemQuantityClicked += TillOrderItemQuantityClicked;
mOrderItemRowList[pIdx - 1].OrderCheckBoxClicked += OrderCheckboxClicked;
mOrderItemRowList[pIdx - 1].Visible = true;
mOrderItemRowList[pIdx - 1].SetOrderType(false);
mOrderItemRowList[pIdx - 1].IsRefund(mIsRefund);
}
[Category("Action")]
[Description("Cust Details clicked.")]
public event TillCustDetailsClickedHandler TillCustDetailsClicked;
protected virtual void OnCustDetailsClicked()
{
if (TillCustDetailsClicked != null)
{
//if(mTillMode != 3)
TillCustDetailsClicked(); // Notify Subscribers
}
}
public void AttachInterface(IOrder pIOrder)
{
mIOrder = pIOrder;
}
public void AttachPresenter(PresenterOrder pPresenter)
{
mPresenterOrder = pPresenter;
}
public void AttachOptions(IOptions pIOptions)
{
}
public void AttachTableControl(RestTable pTable)
{
if (pTable != null)
{
mCurrentTable = pTable;
labTableNo.Text = mCurrentTable.Name;
}
else
{
labTableNo.Text = "0";
labTableCovers.Text = "0";
}
}
public void SetTillMode(decimal pTillMode)
{
mTillMode = pTillMode;
if (mTillMode == 2) // Restaurant Mode
{
labTableNo.Visible = true;
labTableNoDesc.Visible = true;
labTableCovers.Visible = true;
labTableCoversDesc.Visible = true;
labCustName.Visible = false;
labCustNameTitle.Visible = false;
}
else if (mTillMode == 3) // Supermarket Mode
{
// This till mode also stops OnCustDetailsClicked() from firing
labTableNo.Visible = false;
labTableNoDesc.Visible = false;
labTableCovers.Visible = false;
labTableCoversDesc.Visible = false;
labCustName.Visible = false;
labCustNameTitle.Visible = false;
panPhone.Visible = false;
}
else // Takeaway Mode (Default)
{
labTableNo.Visible = false;
labTableNoDesc.Visible = false;
labTableCovers.Visible = false;
labTableCoversDesc.Visible = false;
labCustName.Visible = true;
labCustNameTitle.Visible = true;
}
}
public ORDERTYPE GetOrderType()
{
return mIOrder.mCurrentOrderDetails.OrderType;
}
public void DisplayOrder(bool pRecall, bool pMoveToLast = false)
{
mPresenterOrder.AttachOrderView(this);
mPresenterOrder.AttachOrderItemRowList(mOrderItemRowList);
if (mIOrder.mCurrentOrderItems.Count <= 11 && mIOrder.mCurrentOrderItems.Count > mLastItemCount &&
!pRecall && mTillMode == 3)
mPresenterOrder.ProcessPanelDisplayBETA(false);
else
mPresenterOrder.ProcessPanelDisplay(false, pMoveToLast); // time waster
mLastItemCount = mIOrder.mCurrentOrderItems.Count; // Accumulated Quantity Bug Fix & void ln
// DisplayOrderDetails();
}
public void DisplayOrderDetails()
{
labOrderNo.Text = mIOrder.mCurrentOrderDetails.OrderNo.ToString();
labCustNo.Text = mIOrder.mCurrentOrderDetails.OrderCustDetails.CustNo;
labTableNo.Text = mIOrder.mCurrentOrderDetails.OrderTableNo.ToString();
labTableCovers.Text = mIOrder.mCurrentOrderDetails.OrderTableCovers.ToString();
labCustNameTitle.Visible = false;
labCustName.Text = mIOrder.mCurrentOrderDetails.OrderCustDetails.CustName;
if (labCustName.Text != "")
{
labCustNameTitle.Visible = true;
}
//mPresenterOrder.UpdateTotals();
//labDeliveryAmt.Text = mIOrder.mCurrentOrderDetails.OrderDeliveryTotal.ToString("0.00");
//labDiscountAmt.Text = mIOrder.mCurrentOrderDetails.OrderDiscountPerc.ToString()+"%";
if (mIOrder.mCurrentOrderDetails.OrderDeliveryTotal > 0)
{
labDelivery.Text = "Delivery";
labDelivery.Visible = true;
labDeliveryAmt.Text = mIOrder.mCurrentOrderDetails.OrderDeliveryTotal.ToString("0.00");
}
else if (mTillMode == 3 && mIOrder.mCurrentOrderDetails.OrderQty > 0 &&
mIOrder.mCurrentOrderDetails.OrderVAT == 0)
{
labDelivery.Text = "Item Qty";
labDelivery.Visible = true;
labDeliveryAmt.Text = mIOrder.mCurrentOrderDetails.OrderQty.ToString();
}
else if (mIOrder.mCurrentOrderDetails.OrderVAT > 0)
{
labDelivery.Text = "VAT";
labDelivery.Visible = true;
labDeliveryAmt.Text = mIOrder.mCurrentOrderDetails.OrderVAT.ToString("0.00");
labDelivery.Font = new Font(labNetAmt.Font.FontFamily.Name, labNetAmt.Font.Size);
}
else
{
labDelivery.Visible = false;
labDeliveryAmt.Text = string.Empty;
}
if (mTillMode == 3 && mIOrder.mCurrentOrderDetails.OrderQty > 0 && mIOrder.mCurrentOrderDetails.OrderVAT > 0)
{
labDiscount.Text = "Item Qty";
labDiscount.Visible = true;
labDiscountAmt.Text = mIOrder.mCurrentOrderDetails.OrderQty.ToString();
}
else if (mIOrder.mCurrentOrderDetails.OrderDiscountAmt > 0)
{
labDiscount.Text = "Discount";
labDiscount.Visible = true;
labDiscountAmt.Text = mIOrder.mCurrentOrderDetails.OrderDiscountAmt.ToString("0.00");
}
else
{
labDiscount.Visible = false;
labDiscountAmt.Text = string.Empty;
}
double NetAmount = mIOrder.mCurrentOrderDetails.OrderNET;
// +mIOrder._mCurrentOrderDetails.OrderVAT;
if (mIOrder.mCurrentOrderDetails.OptionAddVATToPrice)
{
labNetAmt.Text = NetAmount.ToString("0.00");
labTotalAmt.Text =
(NetAmount + +mIOrder.mCurrentOrderDetails.OrderVAT +
mIOrder.mCurrentOrderDetails.OrderDeliveryTotal - mIOrder.mCurrentOrderDetails.OrderDiscountAmt)
.ToString("0.00");
}
else
{
labNetAmt.Text = (NetAmount - mIOrder.mCurrentOrderDetails.OrderVAT).ToString("0.00");
labTotalAmt.Text =
(NetAmount + mIOrder.mCurrentOrderDetails.OrderDeliveryTotal -
mIOrder.mCurrentOrderDetails.OrderDiscountAmt).ToString("0.00");
}
if (Convert.ToDouble(labTotalAmt.Text) < 0)
labTotalAmt.Text = "0.00";
CheckPaid();
}
public List<OrderGridItemRow> GetOrderItemRowList()
{
return mOrderItemRowList;
}
public IOrder GetIOrder()
{
return mIOrder;
}
public int GetPanelHeight()
{
return panItems.Height;
}
private void CheckPaid()
{
// RP Sets the total box to the local 'paidBckcolour' if the order displaied has been paid for, if not reverts back to default.
if ((mIOrder.mCurrentOrderDetails.OrderPayment >= mIOrder.mCurrentOrderDetails.OrderTotal) &&
mIOrder.mCurrentOrderDetails.OrderTotal != 0)
{
labDeliveryAmt.BackColor = paidBckcolour;
labDiscountAmt.BackColor = paidBckcolour;
labNetAmt.BackColor = paidBckcolour;
labTotalAmt.BackColor = paidBckcolour;
labDelivery.BackColor = paidBckcolour;
labDiscount.BackColor = paidBckcolour;
labNet.BackColor = paidBckcolour;
labTotal.BackColor = paidBckcolour;
}
else
{
labDeliveryAmt.BackColor = Color.WhiteSmoke;
labDiscountAmt.BackColor = Color.WhiteSmoke;
labNetAmt.BackColor = Color.WhiteSmoke;
labTotalAmt.BackColor = Color.WhiteSmoke;
labDelivery.BackColor = Color.WhiteSmoke;
labDiscount.BackColor = Color.WhiteSmoke;
labNet.BackColor = Color.WhiteSmoke;
labTotal.BackColor = Color.WhiteSmoke;
}
}
private void btnOrderItemGridUp_Click(object sender, EventArgs e)
{
// TODO
bool bFirstItem = false;
int OffsetIdx = 0;
int OrderItemRowListCount = mOrderItemRowList.Count;
if (OrderItemRowListCount > 0)
{
for (int i = 0; i < OrderItemRowListCount; i++)
{
if (mOrderItemRowList[i].Top >= 0)
{
OffsetIdx = i;
break;
}
}
}
mItemGridEndIdx = mItemGridStartIdx + OffsetIdx;
mItemGridStartIdx = mItemGridEndIdx - ITEM_GRID_ROWS;
if (mItemGridStartIdx < 0 && mItemGridEndIdx < ITEM_GRID_ROWS &&
(mItemGridStartIdx + mItemGridEndIdx + OffsetIdx < ITEM_GRID_ROWS))
{
bFirstItem = true;
mItemGridEndIdx = ITEM_GRID_ROWS;
}
if (!bFirstItem)
{
int GridRowOffset = mOrderItemRowList[mLastDisplayedRowIdx].Bottom - panItems.Height;
if (OrderItemRowListCount > 0 && GridRowOffset > 0)
{
for (int i = 0; i < OrderItemRowListCount; i++)
{
mOrderItemRowList[i].Location = new Point(1, mOrderItemRowList[i].Top - GridRowOffset);
}
}
}
setItemGridIndex(mItemGridStartIdx, mItemGridEndIdx);
mPresenterOrder.ProcessPanelDisplay(false);
mLastDisplayedRowIdx = mPresenterOrder.mLastDisplayedRowIdx;
mItemGridStartIdx = mPresenterOrder.mItemGridStartIdx;
mItemGridEndIdx = mPresenterOrder.mItemGridEndIdx;
}
private void btnOrderItemGridDown_Click(object sender, EventArgs e)
{
int OffsetIdx = 0;
int OrderItemListCount = mOrderItemRowList.Count;
if (OrderItemListCount > 0)
{
for (int i = 0; i < OrderItemListCount; i++)
{
if (mOrderItemRowList[i].Bottom > panItems.Height)
{
OffsetIdx = i;
break;
}
}
}
if (OffsetIdx == 0)
{
OffsetIdx = ITEM_GRID_ROWS;
}
if (mItemGridStartIdx + OffsetIdx <= mIOrder.mCurrentOrderItems.Count)
{
mItemGridStartIdx += OffsetIdx;
mItemGridEndIdx = mItemGridStartIdx + ITEM_GRID_ROWS;
setItemGridIndex(mItemGridStartIdx, mItemGridEndIdx);
mPresenterOrder.ProcessPanelDisplay(false);
mLastDisplayedRowIdx = mPresenterOrder.mLastDisplayedRowIdx;
mItemGridStartIdx = mPresenterOrder.mItemGridStartIdx;
mItemGridEndIdx = mPresenterOrder.mItemGridEndIdx;
//mPresenterOrder.DisplayOrderItems(mOrderItemRowList, panItems.Height);
}
}
private void setItemGridIndex(int pStartIndex, int pEndIndex)
{
if (pStartIndex < 0)
pStartIndex = 0;
mPresenterOrder.mItemGridStartIdx = pStartIndex;
mPresenterOrder.mItemGridEndIdx = pEndIndex;
mPresenterOrder.mLastDisplayedRowIdx = mLastDisplayedRowIdx;
// mLastDisplayedRowIdx = mPresenterOrder.mLastDisplayedRowIdx;
}
public void setSplitMode(bool pMode)
{
mSplitMode = pMode;
}
private void labCustNo_Click(object sender, EventArgs e)
{
OnCustDetailsClicked();
}
private void labCustNoDesc_Click(object sender, EventArgs e)
{
OnCustDetailsClicked();
}
private void labCustName_Click(object sender, EventArgs e)
{
OnCustDetailsClicked();
}
private void labCustNameTitle_Click(object sender, EventArgs e)
{
OnCustDetailsClicked();
}
private void labOrderNoDesc_Click(object sender, EventArgs e)
{
OnCustDetailsClicked();
}
private void labOrderNo_Click(object sender, EventArgs e)
{
OnCustDetailsClicked();
}
private void panCustInfo_Click(object sender, EventArgs e)
{
OnCustDetailsClicked();
}
public void TillMark2PrintClicked()
{
if (mIOrder.mCurrentOrderItems.Count > 0 && mCurrentItemRow != null)
{
mCurrentItemRow.SetMark2PrintOrderSelected(true);
foreach (TillOrderItem item in mIOrder.mCurrentOrderItems)
if (item.GetItemID() == mIOrder.mCurrentOrderItemID)
if (!item.GetMarked2Print())
item.SetMark2Print(true);
else
item.SetMark2Print(false);
}
}
public void TillMark2PrintReset()
{
foreach (TillOrderItem item in mIOrder.mCurrentOrderItems)
item.SetMark2Print(false);
}
[Category("Action")]
[Description("Order Item Price Clicked.")]
public event TillOrderPriceClickedHandler TillOrderPriceClicked;
protected virtual void OnTillOrderPriceClicked(Point pKeyPadLoc)
{
if (TillOrderPriceClicked != null)
{
TillOrderPriceClicked(pKeyPadLoc); // Notify Subscribers
}
}
private void TillOrderItemPriceClicked(OrderGridItemRow pOrderItemRow)
{
OnTillOrderPriceClicked(GetRowLocation(pOrderItemRow));
}
private Point GetRowLocation(OrderGridItemRow pOrderItemRow)
{
int mKeyPadX, mKeyPadY;
Point mFloutingKeypadLoc;
mCurrentItemRow = pOrderItemRow;
mKeyPadX = pOrderItemRow.Location.X + pOrderItemRow.Width + 2;
mKeyPadY = pOrderItemRow.Parent.Location.Y + pOrderItemRow.Location.Y + (pOrderItemRow.Height/2);
mPresenterOrder.ClearOrderItemGridSelections(false);
mIOrder.mCurrentOrderItemID = mCurrentItemRow.ItemID;
mFloutingKeypadLoc = new Point(mKeyPadX, mKeyPadY);
return mFloutingKeypadLoc;
}
private bool TillOrderItemPriceLeft(double pNewItemPrice, double pOldItemPrice)
{
if (pOldItemPrice >= 0)
{
if (pNewItemPrice >= 0)
{
if (SetTillItemPrice(pNewItemPrice))
return true;
}
}
else
{
if (pNewItemPrice < 0)
{
if (SetTillItemPrice(pNewItemPrice))
return true;
}
}
return false;
}
private bool SetTillItemPrice(double pNewItemPrice)
{
foreach (TillOrderItem Item in mIOrder.mCurrentOrderItems)
{
if (Item.GetItemID() == mIOrder.mCurrentOrderItemID)
{
Item.SetItemPrice(pNewItemPrice);
mPresenterOrder.UpdateTotals();
DisplayOrder(false);
return true;
}
}
return false;
}
[Category("Action")]
[Description("Order Item Quantity Clicked.")]
public event TillOrderQuantityClickedHandler TillOrderQuantityClicked;
protected virtual void OnTillOrderQuantityClicked(Point pKeyPadLoc)
{
if (TillOrderQuantityClicked != null)
{
TillOrderQuantityClicked(pKeyPadLoc); // Notify Subscribers
}
}
private void TillOrderItemQuantityClicked(OrderGridItemRow pOrderItemRow)
{
OnTillOrderQuantityClicked(GetRowLocation(pOrderItemRow));
}
public void SetItemQty()
{
mCurrentItemRow.RefreshItemRow();
if (mCurrentItemRow.ItemQty == 0)
mCurrentItemRow.ItemQty = 1;
mIOrder.mCurrentOrderItems[
mIOrder.mCurrentOrderItems.FindIndex(i => i.GetItemID() == mIOrder.mCurrentOrderItemID)].SetItemQty(
(int) mCurrentItemRow.ItemQty);
mPresenterOrder.UpdateTotals();
DisplayOrder(false);
}
private void TillOrderItemClicked(OrderGridItemRow pOrderItemRow)
{
mCurrentItemRow = pOrderItemRow;
mPresenterOrder.ClearOrderItemGridSelections(false);
mIOrder.mCurrentOrderItemID = pOrderItemRow.ItemID;
if (mSplitMode)
{
mPresenterOrder.SetAsSplitItem(mIOrder.mCurrentOrderItemID);
DisplayOrder(false);
mPresenterOrder.ProcessPanelDisplay(mSplitMode);
//mPresenterOrder.ProcessPanelDisplay(!mSplitMode);
}
else
{
mCurrentItemRow.SetOrderItemSelected(true);
ShowItemControls(true);
// viewfunc
}
}
public void UpdatePhone()
{
if ((string) picPhone1.Tag == "1")
{
picPhone1.BackgroundImage = Properties.Resources.phone_ringing;
panPhone.BackColor = Color.White;
picPhone1.Tag = "2";
}
else
{
picPhone1.BackgroundImage = Properties.Resources.phone1;
//picPhone1.BackColor = Color.Aqua;
panPhone.BackColor = Color.FromArgb(114, 205, 206);
picPhone1.Tag = "1";
}
}
[Category("Action")]
[Description("Order Item Phone Clicked.")]
public event TillOrderItemPhoneClickedHandler TillOrderItemPhoneClicked;
protected virtual void OnOrderItemPhoneClicked()
{
if (TillOrderItemPhoneClicked != null)
{
TillOrderItemPhoneClicked(); // Notify Subscribers
}
}
private void picPhone1_Click(object sender, EventArgs e)
{
OnOrderItemPhoneClicked();
}
public void ResetPhone()
{
picPhone1.BackgroundImage = Properties.Resources.phone1;
panPhone.BackColor = Color.Aqua;
picPhone1.BackColor = Color.Aqua;
picPhone1.Tag = "1";
}
public int getCurrentTableNo()
{
return Convert.ToInt32(labTableNo.Text);
}
[Category("Action")]
[Description("Order Item Clicked, Show Controls")]
public event TillOrderItemClickedHandler TillShowControls;
protected virtual void OnTillShowControls(bool pOption)
{
if (TillShowControls != null)
{
TillShowControls(true); // Notify Subscribers
}
}
private void OrderCheckboxClicked(OrderItemDetails pOrderItemRow)
{
OnOrderChecked(pOrderItemRow);
}
[Category("Action")]
[Description("Order Checkbox Clicked")]
public event TillOrderCheckBoxClickedHandler OrderChecked;
protected virtual void OnOrderChecked(OrderItemDetails pOrderItemRow)
{
if(OrderChecked != null)
{
OrderChecked(pOrderItemRow);
}
}
private void ShowItemControls(bool pOption)
{
OnTillShowControls(pOption);
}
[Category("Action")]
[Description("Assign Order to Table Clicked.")]
public event TillOrderTableSelectionClickedHandler TillOrderTableSelectionClicked;
protected virtual void OnTillOrderTableSelectionClicked()
{
if (TillOrderTableSelectionClicked != null)
{
TillOrderTableSelectionClicked(); // Notify Subscribers
}
}
private void panTableSel_Click(object sender, EventArgs e)
{
// Table Selections
Console.Write("Table Selection");
OnTillOrderTableSelectionClicked();
}
private void labTableNoDesc_Click(object sender, EventArgs e)
{
Console.Write("Table Selection");
OnTillOrderTableSelectionClicked();
}
private void labTableNo_Click(object sender, EventArgs e)
{
Console.Write("Table Selection");
OnTillOrderTableSelectionClicked();
}
[Category("Action")]
[Description("Assign Customers to Table Clicked.")]
public event TillOrderTableCoverClickedHandler TillOrderTableCoverClicked;
protected virtual void OnTillOrderTableCoverClicked()
{
if (TillOrderTableCoverClicked != null)
{
TillOrderTableCoverClicked(); // Notify Subscribers
}
}
private void panTableCov_Click(object sender, EventArgs e)
{
// No of People on Table, Selections
Console.Write("Table Covers");
OnTillOrderTableCoverClicked();
}
private void labTableCoversDesc_Click(object sender, EventArgs e)
{
Console.Write("Table Covers");
OnTillOrderTableCoverClicked();
}
private void labTableCovers_Click(object sender, EventArgs e)
{
Console.Write("Table Covers");
OnTillOrderTableCoverClicked();
}
}
}
User unable to click button on popup messagebox .This happen when user machine, install the latest .Net framework 4.5 above
public partial class MessageBoxControl
{
private static bool _okClicked;
private static bool _cancelClicked;
private static bool _yesClicked;
private static bool _noClicked;
public static bool IsMsgBoxOpen;
private static Window _win;
private static Grid _container;
private static MessageBoxResult _messageBoxResult;
private static DispatcherTimer _dispatcherTimer;
private static MessageBoxControl _msg;
public static Action<object, RoutedEventArgs> DefaultAction;
private static bool _isVerifySelect = false;
public MessageBoxControl()
{
InitializeComponent();
}
private static void OpenControl()
{
_msg.GdContainer.Height = 0;
_msg.GdContainer.Width = 0;
_dispatcherTimer = new DispatcherTimer();
_dispatcherTimer.Tick += dispatcherTimerOpen_Tick;
_dispatcherTimer.Interval = new TimeSpan(0, 0, 0, 0, 1);
_dispatcherTimer.Start();
}
public static void CloseControl()
{
if (_container != null) _container.IsEnabled = true;
try
{
_dispatcherTimer.Stop();
}
catch { }
_dispatcherTimer = new DispatcherTimer();
_dispatcherTimer.Tick += dispatcherTimerClose_Tick;
_dispatcherTimer.Interval = new TimeSpan(0, 0, 0, 0, 1);
_dispatcherTimer.Start();
}
public static void CloseOnEscape()
{
CloseControl();
}
public static void ExecuteDefaultAction(object obj, RoutedEventArgs e)
{
if (DefaultAction != null)
{
DefaultAction(obj, e);
}
}
private static void dispatcherTimerClose_Tick(object sender, EventArgs e)
{
_msg.MessageContainer.Visibility = Visibility.Hidden;
_msg.ButtonContainer.Visibility = Visibility.Hidden;
_msg.ButtonSelect.Visibility = Visibility.Collapsed;
if ((_msg.GdContainer.Height > 0))
{
_msg.GdContainer.Height = _msg.GdContainer.Height - 20;
}
if ((_msg.GdContainer.Width > 0))
{
_msg.GdContainer.Width = _msg.GdContainer.Width - 30;
}
else
{
_dispatcherTimer.Stop();
_container.Children.Remove(_msg);
IsMsgBoxOpen = false;
}
}
private static void dispatcherTimerOpen_Tick(object sender, EventArgs e)
{
if (!(_msg.GdContainer.Height >= 240))
{
_msg.GdContainer.Height = _msg.GdContainer.Height + 20;
}
if (!(_msg.GdContainer.Width >= 360))
{
_msg.GdContainer.Width = _msg.GdContainer.Width + 30;
}
else
{
_msg.MessageContainer.Visibility = Visibility.Visible;
_msg.ButtonContainer.Visibility = Visibility.Visible;
if (_isVerifySelect)
{
_msg.ButtonSelect.Visibility = Visibility.Visible;
}
_dispatcherTimer.Stop();
}
}
public static MessageBoxResult Show(string message,
MessageBoxButton messageBoxButton = MessageBoxButton.OK,
string iconUrl = null, bool isRed = false, Window currentWindow = null,
bool displayCancelOnly = false, UIElement newObject = null, bool isVerify = false) // testing -- bool displayCancelOnly = false
{
// displayCancelOnly = true; // testing
_isVerifySelect = isVerify;
if (_msg == null)
{
_msg = new MessageBoxControl();
}
if (currentWindow != null)
{
_win = currentWindow;
}
else
{
_win = Application.Current.Windows[0];
}
if (_win != null)
{
_container = LogicalTreeHelper.FindLogicalNode(_win, "GdContainer") as Grid;
if (_container != null)
{
var msgBox = FindChild<MessageBoxControl>(_container, _msg.Name);
if (msgBox == null)
{
//LoginPage lg = new LoginPage();
//if (_win.ToString().Equals(lg.ToString()))
//{
// _msg.Margin = new Thickness(40, 0, 0, 0);
// _container.IsEnabled = false;
// _container.Children.Add(_msg);
// IsMsgBoxOpen = true;
//}
//else
//{
_msg.Margin = new Thickness(0, 0, 0, 0);
_container.IsEnabled = false;
_container.Children.Add(_msg);
IsMsgBoxOpen = true;
//}
//lg.Close();
}
else
{
return MessageBoxResult.Cancel;
}
}
}
Panel.SetZIndex(_msg, 1000);
OpenControl();// To open control in expanding manner
CommonHelper.PlaypopupSound();
//_okClicked = false; // testing
//_cancelClicked = false; // testing
//_yesClicked = false; // testing
//_noClicked = false; // testing
//DefaultAction = null; // testing
_msg.ImgIcon.Visibility = Visibility.Collapsed;
_msg.TxtErrorMessage.Text = message;
if (newObject != null)
{
_msg.TxtErrorMessage.Inlines.Add(newObject);
}
if (isRed)
{
_msg.TxtErrorMessage.Foreground = Brushes.Red;
_msg.TxtErrorMessage.FontSize = 14;
}
if (iconUrl != null)
{
_msg.ImgIcon.Source = new BitmapImage(new Uri(iconUrl, UriKind.RelativeOrAbsolute));
_msg.ImgIcon.Visibility = Visibility.Visible;
}
if (messageBoxButton == MessageBoxButton.OK)
{
_msg.BtnOk.Visibility = Visibility.Visible;
if (_isVerifySelect)
{
_msg.BtnOkSelectFinger.Visibility = Visibility.Visible;
DefaultAction = _msg.OnOkSelectFingerClick;
}
else
DefaultAction = _msg.OnOkClick;
_msg.BtnYes.Visibility = Visibility.Collapsed;
_msg.BtnNo.Visibility = Visibility.Collapsed;
_msg.BtnCancel.Visibility = Visibility.Collapsed;
}
if (messageBoxButton == MessageBoxButton.OKCancel)
{
_msg.BtnOk.Visibility = Visibility.Visible;
_msg.BtnYes.Visibility = Visibility.Collapsed;
_msg.BtnNo.Visibility = Visibility.Collapsed;
_msg.BtnCancel.Visibility = Visibility.Visible;
DefaultAction = _msg.OnOkClick;
}
if (messageBoxButton == MessageBoxButton.YesNo)
{
_msg.BtnOk.Visibility = Visibility.Collapsed;
_msg.BtnYes.Visibility = Visibility.Visible;
_msg.BtnNo.Visibility = Visibility.Visible;
_msg.BtnCancel.Visibility = Visibility.Collapsed;
DefaultAction = _msg.OnYesClick;
}
if (messageBoxButton == MessageBoxButton.YesNoCancel)
{
_msg.BtnOk.Visibility = Visibility.Collapsed;
_msg.BtnYes.Visibility = Visibility.Visible;
_msg.BtnNo.Visibility = Visibility.Visible;
_msg.BtnCancel.Visibility = Visibility.Visible;
DefaultAction = _msg.OnYesClick;
}
if (displayCancelOnly)
{
_msg.BtnOk.Visibility = Visibility.Collapsed;
_msg.BtnYes.Visibility = Visibility.Collapsed;
_msg.BtnNo.Visibility = Visibility.Collapsed;
_msg.BtnCancel.Visibility = Visibility.Visible;
DefaultAction = _msg.OnOkClick;
}
_msg.BtnCancel.ToolTip="Hey";
_msg.BtnNo.ToolTip = "No";
_msg.BtnYes.ToolTip = "yes";
_msg.BtnOk.ToolTip = "ok";
_msg.BtnNo.ToolTip = "No";
//if (currentWindow != null)
//{
// _win = currentWindow;
//}
//else
//{
// _win = Application.Current.Windows[0];
//}
//_win = Application.Current.Windows[0];
if (_win != null)
{
_container = LogicalTreeHelper.FindLogicalNode(_win, "GdContainer") as Grid; //_win.FindName("GdContainer") as Grid;
if (_container != null)
{
var msgBox = FindChild<MessageBoxControl>(_container, _msg.Name);
if (msgBox == null)
{
_container.Children.Add(_msg);
_msg.Focus();
_win.IsEnabled = false;
}
}
}
while (!_okClicked && !_yesClicked && !_noClicked && !_cancelClicked)
{
// Stop the thread if the application is about to close
if (_msg.Dispatcher.HasShutdownStarted ||
_msg.Dispatcher.HasShutdownFinished)
{
break;
}
// Simulate "DoEvents"
_msg.Dispatcher.Invoke(
DispatcherPriority.Background,
new ThreadStart(delegate { }));
Thread.Sleep(20);
}
return _messageBoxResult;
}
private void OnOkClick(object sender, RoutedEventArgs e)
{
_okClicked = true;
_messageBoxResult = MessageBoxResult.OK;
CloseControl();
}
private void OnYesClick(object sender, RoutedEventArgs e)
{
_yesClicked = true;
_messageBoxResult = MessageBoxResult.Yes;
CloseControl();
}
private void OnNoClick(object sender, RoutedEventArgs e)
{
CloseControl();
_noClicked = true;
_messageBoxResult = MessageBoxResult.No;
}
private void OnCancelClick(object sender, RoutedEventArgs e)
{
_cancelClicked = true;
_messageBoxResult = MessageBoxResult.Cancel;
CloseControl();
}
public static T FindChild<T>(DependencyObject parent, string childName)
where T : DependencyObject
{
// Confirm parent and childName are valid.
if (parent == null) return null;
T foundChild = null;
int childrenCount = VisualTreeHelper.GetChildrenCount(parent);
for (int i = 0; i < childrenCount; i++)
{
var child = VisualTreeHelper.GetChild(parent, i);
// If the child is not of the request child type child
T childType = child as T;
if (childType == null)
{
// recursively drill down the tree
foundChild = FindChild<T>(child, childName);
// If the child is found, break so we do not overwrite the found child.
if (foundChild != null) break;
}
else if (!string.IsNullOrEmpty(childName))
{
var frameworkElement = child as FrameworkElement;
// If the child's name is set for search
if (frameworkElement != null && frameworkElement.Name == childName)
{
// if the child's name is of the request name
foundChild = (T)child;
break;
}
}
else
{
// child element found.
foundChild = (T)child;
break;
}
}
return foundChild;
}
private void OnOkSelectFingerClick(object sender, RoutedEventArgs e)
{
_okClicked = true;
_messageBoxResult = MessageBoxResult.Yes;
CloseControl();
}
}
I have a GUI that is linked to several Sensors through COM-Port. I have a Datahandler that makes sure that the received and sent packages have the correct size and content. And then i have a SensorContainer containing all Sensors, firing an event whenever a new sensor is added!
My problem is now:
I need a method, that can initialize all sensors with one click.
And i just cant do it. If I initialize them one by one, it works, but all in one method doesnt work.
My idea is that the packages get mixed and the handler doesnt accept the sensors anymore for initialization. So i tried to make the method wait for the first sensor to be initialized and the proceed, but i have no clue how!
I tried a few things with mulitthreading, but im not really experienced in that field and it didnt work out in the end anyway...
SensorContainerClass:
public static class SensorContainer
{
public static event EventHandler<ContainerEvent> ContainerChanged;
public static ObservableCollection<Sensor> SensorList
{
get { return _sensorList; }
}
public static void AddSensor(Sensor sensor)
{
Sensor sensorExists = GetSensor(sensor.Address);
if (sensorExists == null)
{
Application.Current.Dispatcher.Invoke(() => _sensorList.Add(sensor));
ContainerChanged(null,new ContainerEvent(sensor.Address, true));
}
else
{
Console.WriteLine("It's not possible to add multiple sensors with the same address.");
}
}
public static void RemoveSensor(Sensor sensor)
{
Sensor sensorExists = GetSensor(sensor.Address);
if (sensorExists != null)
{
Application.Current.Dispatcher.Invoke(() => _sensorList.Remove(sensor));
ContainerChanged(null, new ContainerEvent(sensor.Address, false));
}
else
{
Console.WriteLine("No sensor with address " + sensor.Address);
}
}
public static Sensor GetSensor(byte address)
{
foreach (Sensor sensor in _sensorList)
{
if (sensor.Address == address)
{
return sensor;
}
}
return null;
}
// members
private static readonly ObservableCollection<Sensor> _sensorList = new ObservableCollection<Sensor>();
}
DataHandler:
public class DataHandler:ModelBase
{
private const int MAX_TIMER_TIME = 500;
public long answertime_milli;
Timer aTimer;
Stopwatch watch;
Sensor tempSensor;
private byte[] tempFrame;
private bool framePartPendingFlag = false;
public bool framesEqual;
public bool initalisationFlag = false;
public InitType initialisationType;
public byte[] TxFrame
{
get { return txFrame; }
}
public byte TxAddress
{
get { return TxFrame[0]; }
}
public byte TxLength
{
get { return TxFrame[1]; }
}
public byte TxCommand
{
get { return TxFrame[2]; }
}
public byte[] TxData
{
get { return TxFrame.GetRange(3, TxLength - 2); }
}
public byte TxChecksum
{
get { return TxFrame[TxLength - 1]; }
}
private byte[] txFrame;
private bool successfull;
public bool Successfull
{
get
{
return successfull;
}
set
{
if(successfull != value)
{
successfull = value;
this.OnPropertyChanged();
}
}
}
public DataHandler()
{
txFrame = new byte[4] { 0, 0, 0, 0 };
aTimer = new Timer(MAX_TIMER_TIME);
watch = new Stopwatch();
CommandManager.Instance.Init();
InterfaceWrapper.Instance.SerialPort.DataReceived += OnSerialPortReceived;
}
public void InitializeSensor(InitType type, byte address, Int32 serialNumber = 0)
{
if (SensorContainer.GetSensor(address) != null )
{
MessageBox.Show("Sensoraddress already used");
return;
}
foreach(Sensor temp in SensorContainer.SensorList)
{
if(temp.Serialnr == serialNumber)
{
MessageBox.Show("Sensor with the same SerialNumber already initalized");
return;
}
}
byte[] frame;
if (type == InitType.INIT_TO_ONE_DEVICE)
{
Sensor.COM_ADDR_SET_ONE_TX initStruct = new Sensor.COM_ADDR_SET_ONE_TX();
initStruct.Address = address;
frame = createFrame(initStruct, 0xFF, 0x20);
}
else
{
Sensor.COM_ADDR_SET_TO_SN_TX initStruct = new Sensor.COM_ADDR_SET_TO_SN_TX();
initStruct.Address = address;
if (serialNumber == 0)
{
MessageBox.Show("Serialnumber is missing");
return;
}
initStruct.SerialNumber = serialNumber;
frame = createFrame(initStruct, 0x00, 0x22);
}
setTxFrame(frame);
InterfaceWrapper.Instance.SerialPort.SendData(frame);
initalisationFlag = true;
initialisationType = type;
}
public void StartDataTransfer(Sensor sensor, byte commandid)
{
if (sensor == null)
{
MessageBox.Show("No such sensor");
return;
}
Command command = sensor.getCommand(commandid);
if (command == null)
{
MessageBox.Show("Command does not exist");
return;
}
foreach (KeyValuePair<CommandAttribute, Command> pair in sensor.CommandList)
{
if (pair.Value == command)
{
timeout = pair.Key.Timeout;
transmission = pair.Key.Transmission;
break;
}
}
tempSensor = sensor;
if (SensorContainer.GetSensor(sensor.Address) != null)
{
byte[] endFrame = createFrame(command, sensor.Address, commandid);
setTxFrame(endFrame);
if (true)
{
InterfaceWrapper.Instance.SerialPort.SendData(txFrame);
}
}
else
{
MessageBox.Show("Sensor not yet initialized");
}
}
private byte[] createFrame(Command command, byte address, byte commandId)
{
byte[] data = MarshalHelper.Serialize(command);
byte[] frame = new byte[4 + data.Length];
frame[0] = address;
frame[1] = (byte)frame.Length;
frame[2] = commandId;
Buffer.BlockCopy(data, 0, frame, 3, data.Length);
frame[frame.Length - 1] = GenerateChecksum(frame);
return frame;
}
public void OnSerialPortReceived(object sender, ComDataRxEvent e)
{
byte[] data = e.Data;
setRxFrame(data);
}
public void setTxFrame(byte[] _txFrame)
{
Successfull = false;
txFrame = _txFrame;
aTimer.Elapsed += OnTimedEvent;
aTimer.AutoReset = false;
aTimer.Start();
watch.Start();
}
public void setRxFrame(byte[] _rxFrame)
{
if (framePartPendingFlag)
{
byte[] newTempFrame = new byte[tempFrame.Length + _rxFrame.Length];
tempFrame.CopyTo(newTempFrame, 0);
_rxFrame.CopyTo(newTempFrame, tempFrame.Length);
framePartPendingFlag = false;
setRxFrame(newTempFrame);
}
else if (!checkMinLength(_rxFrame))
{
tempFrame = _rxFrame;
framePartPendingFlag = true;
}
else if (!checkBit(_rxFrame))
{
tempFrame = _rxFrame;
framePartPendingFlag = true;
}
else
{
framePartPendingFlag = false;
aTimer.Stop();
watch.Stop();
answertime_milli = watch.ElapsedMilliseconds;
if (!initalisationFlag)
{
if (checkAll(_rxFrame))
{
writeCommandToSensor(_rxFrame);
}
}
else
{
createSensorAfterInitialization(_rxFrame);
}
}
}
private void writeCommandToSensor(byte[] frame)
{
Command expCommand = CommandManager.Instance.GetRxCommand(tempSensor.GetType(), TxCommand);
Command command = MarshalHelper.Deserialize(expCommand, frame.GetRange(3, frame[1] - 2));
tempSensor.setCommand(command);
}
private void createSensorAfterInitialization(byte[] frame)
{
if (initalisationFlag && initialisationType == InitType.INIT_TO_ONE_DEVICE)
{
Sensor.COM_ADDR_SET_ONE_RX expCommand = new Sensor.COM_ADDR_SET_ONE_RX();
Sensor.COM_ADDR_SET_ONE_RX command = (Sensor.COM_ADDR_SET_ONE_RX)MarshalHelper.Deserialize(expCommand, frame.GetRange(3, frame[1] - 2));
Sensor tempSensor = Sensor.GetSensorInstance(command.SerialNumber, command.Address, command.SensorName, command.SensorSubName, command.dataStructType, command.dataStructSubType,command.pcbVersion,command.firmware);
tempSensor.setCommand(command);
SensorContainer.AddSensor(tempSensor);
initalisationFlag = false;
}
else
{
Sensor.COM_ADDR_SET_TO_SN_RX expCommand = new Sensor.COM_ADDR_SET_TO_SN_RX();
Sensor.COM_ADDR_SET_TO_SN_RX command = (Sensor.COM_ADDR_SET_TO_SN_RX)MarshalHelper.Deserialize(expCommand, frame.GetRange(3, frame[1] - 2));
if (command == null)
{
MessageBox.Show("Sensor not answering");
}
else {
Sensor tempSensor = Sensor.GetSensorInstance(command.SerialNumber, command.Address, command.SensorName, command.SensorSubName, command.dataStructType, command.dataStructSubType, command.pcbVersion, command.firmware);
tempSensor.setCommand(command);
SensorContainer.AddSensor(tempSensor);
initalisationFlag = false;
}
}
}
public void OnTimedEvent(object source, ElapsedEventArgs e)
{
framePartPendingFlag = false;
}
}
I'm stuck with some legacy code that I want to upgrade a bit. I want to change the way the ErrorProvider shows the error status on a Control. Default behavior is the Icon, and a ToolTip if you hover on the icon.
I would like to change this behavior to be more similar to what we use in our WPF controls. Which is a red back-color(Salmon pink) and the tool-tip on the control itself.
Any tips, links or some way forward
EDIT.
See my answer below, on what i ended up with.
ErrorProvider component doesn't support this feature and if you need it you can create it yourself.
You can subscribe to BindingComplete event of a BindingManagerBase and then you can use the event arg which is of type BindingCompleteEventArgs that contains some useful properties:
ErrorText to determine if there is an error in data-binding
Binding.Control to determine the control which is bounded to
These are enough for us to implement our solution.
Code
Here is a sample code which shows how can you handle BindingComplete event and use it to change BackColor and tool-tip of a control based on it's valid or invalid state.
Suppose you have a binding source, myBindingSource which is bound to a SampleModel class which is implemented IDataErrorInfo. You can subscribe to BindingComplete event of this.BindingContext[this.myBindingSource]:
private void Form1_Load(object sender, EventArgs e)
{
this.myBindingSource.DataSource = new SampleModel();
var bindingManager = this.BindingContext[this.myBindingSource];
bindingManager.BindingComplete += bindingManager_BindingComplete;
}
Dictionary<Control, Color> Items = new Dictionary<Control, Color>();
private void bindingManager_BindingComplete(object sender, BindingCompleteEventArgs e)
{
var control = e.Binding.Control;
//Store Original BackColor
if (!Items.ContainsKey(control))
Items[control] = control.BackColor;
//Check If there is an error
if (!string.IsNullOrEmpty(e.ErrorText))
{
control.BackColor = Color.Salmon;
this.errorToolTip.SetToolTip(control, e.ErrorText);
}
else
{
e.Binding.Control.BackColor = Items[e.Binding.Control];
this.errorToolTip.SetToolTip(control, null);
}
}
Thank you Reza Aghaei. This is what i came up with based on your comment and some additional searching... Some of this code comes from msdn resource
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.Drawing;
using System.Linq;
using System.Security.Permissions;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace ErrorProvider
{
class BackgroundColorErrorProvider: Component, IExtenderProvider, ISupportInitialize
{
public BackgroundColorErrorProvider()
{
currentChanged = new EventHandler(ErrorManager_CurrentChanged);
}
public BackgroundColorErrorProvider(ContainerControl parentControl)
: this()
{
this.parentControl = parentControl;
propChangedEvent = new EventHandler(ParentControl_BindingContextChanged);
parentControl.BindingContextChanged += propChangedEvent;
}
public BackgroundColorErrorProvider(IContainer container)
: this()
{
if (container == null) {
throw new ArgumentNullException("container");
}
container.Add(this);
}
public bool CanExtend(object extendee)
{
return extendee is Control && !(extendee is Form) && !(extendee is ToolBar);
}
private bool inSetErrorManager = false;
private object dataSource;
private string dataMember = null;
private ContainerControl parentControl;
private BindingManagerBase errorManager;
private bool initializing;
private EventHandler currentChanged;
private EventHandler propChangedEvent;
private Dictionary<Control, Color> originalColor = new Dictionary<Control, Color>();
private Color errorBackgroundColor;
public ContainerControl ContainerControl
{
[UIPermission(SecurityAction.LinkDemand, Window = UIPermissionWindow.AllWindows)]
[UIPermission(SecurityAction.InheritanceDemand, Window = UIPermissionWindow.AllWindows)]
get
{
return parentControl;
}
set
{
if (parentControl != value)
{
if (parentControl != null)
parentControl.BindingContextChanged -= propChangedEvent;
parentControl = value;
if (parentControl != null)
parentControl.BindingContextChanged += propChangedEvent;
Set_ErrorManager(this.DataSource, this.DataMember, true);
}
}
}
public string DataMember
{
get { return dataMember; }
set
{
if (value == null) value = "";
Set_ErrorManager(this.DataSource, value, false);
}
}
public object DataSource
{
get { return dataSource; }
set
{
if ( parentControl != null && value != null && String.IsNullOrEmpty(this.dataMember))
{
// Let's check if the datamember exists in the new data source
try
{
errorManager = parentControl.BindingContext[value, this.dataMember];
}
catch (ArgumentException)
{
// The data member doesn't exist in the data source, so set it to null
this.dataMember = "";
}
}
Set_ErrorManager(value, this.DataMember, false);
}
}
public override ISite Site
{
set
{
base.Site = value;
if (value == null)
return;
IDesignerHost host = value.GetService(typeof(IDesignerHost)) as IDesignerHost;
if (host != null)
{
IComponent baseComp = host.RootComponent;
if (baseComp is ContainerControl)
{
this.ContainerControl = (ContainerControl)baseComp;
}
}
}
}
private ToolTip toolTip;
public ToolTip ToolTip
{
get { return toolTip; }
set { toolTip = value; }
}
public Color ErrorBackgroundColor
{
get { return errorBackgroundColor; }
set { errorBackgroundColor = value; }
}
private void Set_ErrorManager(object newDataSource, string newDataMember, bool force)
{
if (inSetErrorManager)
return;
inSetErrorManager = true;
try
{
bool dataSourceChanged = this.DataSource != newDataSource;
bool dataMemberChanged = this.DataMember != newDataMember;
//if nothing changed, then do not do any work
//
if (!dataSourceChanged && !dataMemberChanged && !force)
{
return;
}
// set the dataSource and the dataMember
//
this.dataSource = newDataSource;
this.dataMember = newDataMember;
if (!initializing)
{
UnwireEvents(errorManager);
// get the new errorManager
//
if (parentControl != null && this.dataSource != null && parentControl.BindingContext != null)
{
errorManager = parentControl.BindingContext[this.dataSource, this.dataMember];
}
else
{
errorManager = null;
}
// wire the events
//
WireEvents(errorManager);
// see if there are errors at the current
// item in the list, w/o waiting for the position to change
if (errorManager != null)
UpdateBinding();
}
}
finally
{
inSetErrorManager = false;
}
}
public void UpdateBinding()
{
ErrorManager_CurrentChanged(errorManager, EventArgs.Empty);
}
private void UnwireEvents(BindingManagerBase listManager)
{
if (listManager != null)
{
listManager.CurrentChanged -= currentChanged;
listManager.BindingComplete -= new BindingCompleteEventHandler(this.ErrorManager_BindingComplete);
CurrencyManager currManager = listManager as CurrencyManager;
if (currManager != null)
{
currManager.ItemChanged -= new ItemChangedEventHandler(this.ErrorManager_ItemChanged);
currManager.Bindings.CollectionChanged -= new CollectionChangeEventHandler(this.ErrorManager_BindingsChanged);
}
}
}
private void WireEvents(BindingManagerBase listManager)
{
if (listManager != null)
{
listManager.CurrentChanged += currentChanged;
listManager.BindingComplete += new BindingCompleteEventHandler(this.ErrorManager_BindingComplete);
CurrencyManager currManager = listManager as CurrencyManager;
if (currManager != null)
{
currManager.ItemChanged += new ItemChangedEventHandler(this.ErrorManager_ItemChanged);
currManager.Bindings.CollectionChanged += new CollectionChangeEventHandler(this.ErrorManager_BindingsChanged);
}
}
}
private void ErrorManager_BindingsChanged(object sender, CollectionChangeEventArgs e)
{
ErrorManager_CurrentChanged(errorManager, e);
}
private void ParentControl_BindingContextChanged(object sender, EventArgs e)
{
Set_ErrorManager(this.DataSource, this.DataMember, true);
}
private void ErrorManager_ItemChanged(object sender, ItemChangedEventArgs e)
{
BindingsCollection errBindings = errorManager.Bindings;
int bindingsCount = errBindings.Count;
// If the list became empty then reset the errors
if (e.Index == -1 && errorManager.Count == 0)
{
for (int j = 0; j < bindingsCount; j++)
{
if ((errBindings[j].Control != null))
{
// ...ignore everything but bindings to Controls
SetError(errBindings[j].Control, "");
}
}
}
else
{
ErrorManager_CurrentChanged(sender, e);
}
}
private void SetError(Control control, string p)
{
if (String.IsNullOrEmpty(p))
{
if (originalColor.ContainsKey(control))
control.BackColor = originalColor[control];
toolTip.SetToolTip(control, null);
}
else
{
control.BackColor = ErrorBackgroundColor;
toolTip.SetToolTip(control, p);
}
}
private void ErrorManager_BindingComplete(object sender, BindingCompleteEventArgs e)
{
Binding binding = e.Binding;
if (binding != null && binding.Control != null)
{
SetError(binding.Control, (e.ErrorText == null ? String.Empty : e.ErrorText));
}
}
private void ErrorManager_CurrentChanged(object sender, EventArgs e)
{
if (errorManager.Count == 0)
{
return;
}
object value = errorManager.Current;
if (!(value is IDataErrorInfo))
{
return;
}
BindingsCollection errBindings = errorManager.Bindings;
int bindingsCount = errBindings.Count;
// We can only show one error per control, so we will build up a string...
//
Hashtable controlError = new Hashtable(bindingsCount);
for (int j = 0; j < bindingsCount; j++)
{
// Ignore everything but bindings to Controls
if (errBindings[j].Control == null)
{
continue;
}
string error = ((IDataErrorInfo)value)[errBindings[j].BindingMemberInfo.BindingField];
if (error == null)
{
error = "";
}
string outputError = "";
if (controlError.Contains(errBindings[j].Control))
outputError = (string)controlError[errBindings[j].Control];
// VSWhidbey 106890: Utilize the error string without including the field name.
if (String.IsNullOrEmpty(outputError))
{
outputError = error;
}
else
{
outputError = string.Concat(outputError, "\r\n", error);
}
controlError[errBindings[j].Control] = outputError;
}
IEnumerator enumerator = controlError.GetEnumerator();
while (enumerator.MoveNext())
{
DictionaryEntry entry = (DictionaryEntry)enumerator.Current;
SetError((Control)entry.Key, (string)entry.Value);
}
}
public void BeginInit()
{
initializing = true;
}
public void EndInit()
{
initializing = false;
Set_ErrorManager(this.DataSource, this.DataMember, true);
}
}
}
This is my code
gridView1.Columns.Add(new DevExpress.XtraGrid.Columns.GridColumn()
{
Caption = "Selected",
ColumnEdit = new RepositoryItemCheckEdit() { },
VisibleIndex = 1,
UnboundType = DevExpress.Data.UnboundColumnType.Boolean
});
But I cant check multiple checkEdit at the same time.
Why was that?
And please show me the way out.
Thanks.
Well, there are two answers to that question, one very simple, and one very complex, let's start with the simple:
If you want to have an column that has the "Selected" caption and act as a checkbox to indicate that a particular record was selected, you have two options:
1) If you can alter the class in your data source to add a property that is bool and could be used with DataBinding, then, all is done in a very simple way, jast add the property and bind the data and it will work:
class SimplePerson
{
public string Name { get; set; }
public bool IsSelected { get; set; }
}
BindingList<SimplePerson> source = new BindingList<SimplePerson>();
void InitGrid()
{
source.Add(new SimplePerson() { Name = "John", IsSelected = false });
source.Add(new SimplePerson() { Name = "Gabriel", IsSelected = true });
gridControl.DataSource = source;
}
2) You cannot alter you classes, so you need to this by signing the correct grid events and drawing the column yourself, and also adding the right handlers for all the actions.... is a very complex case, but for your luck i have this done, because i have had this problem in the past, so i will post you my full class!
public class GridCheckMarksSelection
{
public event EventHandler SelectionChanged;
protected GridView _view;
protected ArrayList _selection;
private GridColumn _column;
private RepositoryItemCheckEdit _edit;
public GridView View
{
get { return _view; }
set
{
if (_view == value)
return;
if (_view != null)
Detach();
_view = value;
Attach();
}
}
public GridColumn CheckMarkColumn { get { return _column; } }
public int SelectedCount { get { return _selection.Count; } }
public GridCheckMarksSelection()
{
_selection = new ArrayList();
}
public GridCheckMarksSelection(GridView view)
: this()
{
this.View = view;
}
protected virtual void Attach()
{
if (View == null)
return;
_selection.Clear();
_view = View;
_edit = View.GridControl.RepositoryItems.Add("CheckEdit")
as RepositoryItemCheckEdit;
_edit.EditValueChanged += edit_EditValueChanged;
_column = View.Columns.Insert(0);
_column.OptionsColumn.AllowSort = DefaultBoolean.False;
_column.VisibleIndex = int.MinValue;
_column.FieldName = "CheckMarkSelection";
_column.Caption = "Mark";
_column.OptionsColumn.ShowCaption = false;
_column.UnboundType = UnboundColumnType.Boolean;
_column.ColumnEdit = _edit;
View.CustomDrawColumnHeader += View_CustomDrawColumnHeader;
View.CustomDrawGroupRow += View_CustomDrawGroupRow;
View.CustomUnboundColumnData += view_CustomUnboundColumnData;
View.MouseUp += view_MouseUp;
}
protected virtual void Detach()
{
if (_view == null)
return;
if (_column != null)
_column.Dispose();
if (_edit != null)
{
_view.GridControl.RepositoryItems.Remove(_edit);
_edit.Dispose();
}
_view.CustomDrawColumnHeader -= View_CustomDrawColumnHeader;
_view.CustomDrawGroupRow -= View_CustomDrawGroupRow;
_view.CustomUnboundColumnData -= view_CustomUnboundColumnData;
_view.MouseDown -= view_MouseUp;
_view = null;
}
protected virtual void OnSelectionChanged(EventArgs e)
{
if (SelectionChanged != null)
SelectionChanged(this, e);
}
protected void DrawCheckBox(Graphics g, Rectangle r, bool Checked)
{
var info = _edit.CreateViewInfo() as CheckEditViewInfo;
var painter = _edit.CreatePainter() as CheckEditPainter;
ControlGraphicsInfoArgs args;
info.EditValue = Checked;
info.Bounds = r;
info.CalcViewInfo(g);
args = new ControlGraphicsInfoArgs(info, new GraphicsCache(g), r);
painter.Draw(args);
args.Cache.Dispose();
}
private void view_MouseUp(object sender, MouseEventArgs e)
{
if (e.Clicks == 1 && e.Button == MouseButtons.Left)
{
GridHitInfo info;
var pt = _view.GridControl.PointToClient(Control.MousePosition);
info = _view.CalcHitInfo(pt);
if (info.InRow && _view.IsDataRow(info.RowHandle))
UpdateSelection();
if (info.InColumn && info.Column == _column)
{
if (SelectedCount == _view.DataRowCount)
ClearSelection();
else
SelectAll();
}
if (info.InRow && _view.IsGroupRow(info.RowHandle)
&& info.HitTest != GridHitTest.RowGroupButton)
{
bool selected = IsGroupRowSelected(info.RowHandle);
SelectGroup(info.RowHandle, !selected);
}
}
}
private void View_CustomDrawColumnHeader
(object sender, ColumnHeaderCustomDrawEventArgs e)
{
if (e.Column != _column)
return;
e.Info.InnerElements.Clear();
e.Painter.DrawObject(e.Info);
DrawCheckBox(e.Graphics, e.Bounds, SelectedCount == _view.DataRowCount);
e.Handled = true;
}
private void View_CustomDrawGroupRow
(object sender, RowObjectCustomDrawEventArgs e)
{
var info = e.Info as GridGroupRowInfo;
info.GroupText = " " + info.GroupText.TrimStart();
e.Info.Paint.FillRectangle
(e.Graphics, e.Appearance.GetBackBrush(e.Cache), e.Bounds);
e.Painter.DrawObject(e.Info);
var r = info.ButtonBounds;
r.Offset(r.Width * 2, 0);
DrawCheckBox(e.Graphics, r, IsGroupRowSelected(e.RowHandle));
e.Handled = true;
}
private void view_CustomUnboundColumnData
(object sender, CustomColumnDataEventArgs e)
{
if (e.Column != CheckMarkColumn)
return;
if (e.IsGetData)
e.Value = IsRowSelected(View.GetRowHandle(e.ListSourceRowIndex));
else
SelectRow(View.GetRowHandle(e.ListSourceRowIndex), (bool)e.Value);
}
private void edit_EditValueChanged(object sender, EventArgs e)
{
_view.PostEditor();
}
private void SelectRow(int rowHandle, bool select, bool invalidate)
{
if (IsRowSelected(rowHandle) == select)
return;
object row = _view.GetRow(rowHandle);
if (select)
_selection.Add(row);
else
_selection.Remove(row);
if (invalidate)
Invalidate();
OnSelectionChanged(EventArgs.Empty);
}
public object GetSelectedRow(int index)
{
return _selection[index];
}
public int GetSelectedIndex(object row)
{
return _selection.IndexOf(row);
}
public void ClearSelection()
{
_selection.Clear();
View.ClearSelection();
Invalidate();
OnSelectionChanged(EventArgs.Empty);
}
private void Invalidate()
{
_view.CloseEditor();
_view.BeginUpdate();
_view.EndUpdate();
}
public void SelectAll()
{
_selection.Clear();
var dataSource = _view.DataSource as ICollection;
if (dataSource != null && dataSource.Count == _view.DataRowCount)
_selection.AddRange(dataSource); // fast
else
for (int i = 0; i < _view.DataRowCount; i++) // slow
_selection.Add(_view.GetRow(i));
Invalidate();
OnSelectionChanged(EventArgs.Empty);
}
public void SelectGroup(int rowHandle, bool select)
{
if (IsGroupRowSelected(rowHandle) && select) return;
for (int i = 0; i < _view.GetChildRowCount(rowHandle); i++)
{
int childRowHandle = _view.GetChildRowHandle(rowHandle, i);
if (_view.IsGroupRow(childRowHandle))
SelectGroup(childRowHandle, select);
else
SelectRow(childRowHandle, select, false);
}
Invalidate();
}
public void SelectRow(int rowHandle, bool select)
{
SelectRow(rowHandle, select, true);
}
public bool IsGroupRowSelected(int rowHandle)
{
for (int i = 0; i < _view.GetChildRowCount(rowHandle); i++)
{
int row = _view.GetChildRowHandle(rowHandle, i);
if (_view.IsGroupRow(row))
if (!IsGroupRowSelected(row))
return false;
else
if (!IsRowSelected(row))
return false;
}
return true;
}
public bool IsRowSelected(int rowHandle)
{
if (_view.IsGroupRow(rowHandle))
return IsGroupRowSelected(rowHandle);
object row = _view.GetRow(rowHandle);
return GetSelectedIndex(row) != -1;
}
public void UpdateSelection()
{
_selection.Clear();
Array.ForEach(View.GetSelectedRows(), item => SelectRow(item, true));
}
}
And now you need to know how to use this:
void InitGrid()
{
gridControl.DataSource = source;
// Do this after the database for the grid is set!
selectionHelper = new GridCheckMarksSelection(gridView1);
// Define where you want the column (0 = first)
selectionHelper.CheckMarkColumn.VisibleIndex = 0;
// You can even subscrive to the event that indicates that
// there was change in the selection.
selectionHelper.SelectionChanged += selectionHelper_SelectionChanged;
}
void selectionHelper_SelectionChanged(object sender, EventArgs e)
{
// Do something when the user selects or unselects something
}
But how do you retrieve all the selected items? There is a example assuming that the type bond is 'Person'
/// <summary>
/// Return all selected persons from the Grid
/// </summary>
public IList<Person> GetItems()
{
var ret = new List<Person>();
Array.ForEach
(
gridView1.GetSelectedRows(),
cell => ret.Add(gridView1.GetRow(cell) as Person)
);
return ret;
}