I am doing MVC and I am new at it. I am making a game where 5 dice roll by clicking on the 'roll dice' button and show random numbers. Under each die label there is a check box. If the player clicks on the check box the dice don't roll again and the other dice do roll.
I can show dice numbers in my view but I don't understand how to make it so the dice don't roll if you check the checkbox. I translated my program because it's in dutch: Waarde=value; dobbesteen=dice; werp=throw.
public class Dobbelsteen
{
Random rnd = new Random();
public int Waarde { get; set; }
public bool Checked { get; set; }
public int Worpen { get; set; }
public void Rollen()
{
if (Checked == false)
Waarde = rnd.Next(1, 7);
}
}
public class BusinessController
{
List<int> dice = new List<int>();
Dobbelsteen objdobbelsteen = new Dobbelsteen();
public BusinessController()
{
}
public int Roll()
{
for (int i = 0; i < 5; i++)
{
objdobbelsteen.Rollen();
dice.Add(i);
}
return objdobbelsteen.Waarde;
}
public int Werp()
{
objdobbelsteen.Worpen++;
return objdobbelsteen.Worpen;
}
public int nietroll()
{
int i = 1;
return i;
}
/*public bool Winnaar()
{
if (dice[1] == dice[2])
{
return true;
}
else return false;
}*/
public void SetLock(int p)
{
if(objdobbelsteen.Checked==false)
{
nietroll();
}
}
}
public partial class Form1 : Form
{
BusinessController busniessController = new BusinessController();
public Form1()
{
InitializeComponent();
}
public void Gooien_Click(object sender, EventArgs e)
{
lblWorpen.Text = Convert.ToString(busniessController.Werp());
dblsteen1.Text = Convert.ToString(busniessController.Roll());
dblsteen2.Text = Convert.ToString(busniessController.Roll());
dblsteen3.Text = Convert.ToString(busniessController.Roll());
dblsteen4.Text = Convert.ToString(busniessController.Roll());
dblsteen5.Text = Convert.ToString(busniessController.Roll());
if (dblsteen1.Text==dblsteen2.Text)
MessageBox.Show("u win");
}
public void checkBox1_CheckedChanged(object sender, EventArgs e)
{
busniessController.SetLock(1);
}
private void checkBox2_CheckedChanged(object sender, EventArgs e)
{
busniessController.SetLock(2);
}
private void checkBox3_CheckedChanged(object sender, EventArgs e)
{
busniessController.SetLock(3);
}
private void checkBox4_CheckedChanged(object sender, EventArgs e)
{
busniessController.SetLock(4);
}
private void checkBox5_CheckedChanged(object sender, EventArgs e)
{
busniessController.SetLock(5);
}
}
You need 5 different dices, not just one. In this way each dice can have its own Checked property set to a different value
List<Dobbelsteen> dices = new List<Dobbelsteen>()
{
{new Dobbelsteen()},
{new Dobbelsteen()},
{new Dobbelsteen()},
{new Dobbelsteen()},
{new Dobbelsteen()}
};
public void RollAll()
{
for (int i = 0; i < 5; i++)
dices[i].Rollen();
}
public int GetDiceValue(int i)
{
if(i >= 0 && i <= dices.Count)
return dices[i].Waarde;
else
throw new IndexOutOfRangeException($"Invalid index {i}");
}
public void SetLock(int p)
{
if(p >= 0 && p <= dices.Count)
return dices[p].Checked = true;
else
throw new IndexOutOfRangeException($"Invalid index {p}");
}
Also you should make your Random variable of the class DobbelSteen static otherwise the strict loop inside the Rollen method results in the same value returned for every dice.
After this you can call
busniessController.RollAll();
dblsteen1.Text = busniessController.GetDiceValue(0).ToString();
dblsteen2.Text = busniessController.GetDiceValue(1).ToString();
dblsteen3.Text = busniessController.GetDiceValue(2).ToString();
dblsteen4.Text = busniessController.GetDiceValue(3).ToString();
dblsteen5.Text = busniessController.GetDiceValue(4).ToString();
Finally remember that in NET the index for a collection like a list starts at zero and ends to the collection count - 1. So your call to SetLock should be changed accordingly to avoid the exception
You never actually set the "Checked" value, SetLock refers to the nietRol function which just sets an int. Here you need to set the "Checked" value to true.
And please programmeer niet in het Nederlands maar doe alles in het Engels.
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();
}
}
}
I have a dynamical create button object where I want it to send an event to the mainform when I click on a button inside this object.
I have the code like this :
class Class1
{
internal class FObj_BtnRow
{
private Button[] _Btnmembers;
internal event EventHandler<SelValue_EArgs>[] e_BtnMember; //subscribe to a change
internal class SelValue_EArgs : EventArgs//events args (selected value)
{//return arguments in events
internal SelValue_EArgs(Boolean ivalue) { refreshed = ivalue; }//ctor
internal Boolean refreshed { get; set; }//accessors
}
private Boolean[] _ActONOFFValue; //Pump=0, valveInput = 1, Shower = 3, Washtool = 4 , WashWPcs = 5
private Boolean ActONOFFValue(int number)
{
_ActONOFFValue[number] = !_ActONOFFValue[number];
{
if (e_BtnMember[number] != null && number == 0) e_BtnMember[number](this, new SelValue_EArgs(_ActONOFFValue[number]));
}
return _ActONOFFValue[number];
}
public FObj_BtnRow(String[] TxtBtn, String UnitName)//ctor
{
_Btnmembers = new Button[TxtBtn.Length];
e_BtnMember = new EventHandler<SelValue_EArgs>[TxtBtn.Length];
for (int i = 0; i < TxtBtn.Length / 2; i++)
{
_Btnmembers[i].Click += new EventHandler(_Btnmembers_Click);
}
}
protected virtual void _Btnmembers_Click(object sender, EventArgs e)
{
int index = Array.IndexOf(_Btnmembers, (Button)sender);
ActONOFFValue(index);
}
}
}
But in the line : internal event EventHandler[] e_BtnMember;
the compiler told me that I should use a delegate. I don't understand good this remark, could you help me?
At the end the mainform should only subscribe to the event button click it wants.
And then in main we could use it to now when a button in the object multibutton row is clicked... like this:
public void main()
{
String[] txtbtn = new String[] { "btn1", "btn2", "btn3" };
FObj_BtnRow thisbtnrow = new FObj_BtnRow(txtbtn);
thisbtnrow.e_BtnMember[0] += new EventHandler<FObj_BtnRow.SelValue_EArgs> (btnmember0haschanged);
}
public void btnmember0haschanged(object sender, FObj_BtnRow.SelValue_EArgs newvalue)
{
bool thisnewvalue = newvalue.refreshed;
}
Can you help me?
Thanks in advance!!
I solved the problem by myself, thanks for your advices.
Code
class Class1
{
internal class FObj_BtnRowtest
{
private Button[] _Btnmembers;
public delegate void del_Btnmember(Boolean value);
public del_Btnmember[] btnvaluechanged;
internal class SelValue_EArgs : EventArgs//events args (selected value)
{//return boolean arguments in events
internal SelValue_EArgs(Boolean ivalue) { refreshed = ivalue; }//ctor
internal Boolean refreshed { get; set; }//accessors
}
private Boolean[] _ActONOFFValue;
private Boolean ActONOFFValue(int number)
{
_ActONOFFValue[number] = !_ActONOFFValue[number];
return _ActONOFFValue[number];
}
public FObj_BtnRowtest(int numofbtn, String UnitName)//ctor
{
_Btnmembers = new Button[numofbtn];
btnvaluechanged = new del_Btnmember[numofbtn];
_ActONOFFValue = new bool[numofbtn];
for (int i = 0; i < numofbtn / 2; i++)
{
_Btnmembers[i].Click += new EventHandler(_Btnmembers_Click);
}
}
protected virtual void _Btnmembers_Click(object sender, EventArgs e)
{
int index = Array.IndexOf(_Btnmembers, (Button)sender);
if (btnvaluechanged[index] != null) btnvaluechanged[index](ActONOFFValue(index));
}
}
}
And then in main
thisrow = new Class1.FObj_BtnRowtest(4,"thisunittest");//4 buttons
thisrow.btnvaluechanged[0] += new Class1.FObj_BtnRowtest.del_Btnmember(valuetesthaschanged);//to subscribe to btn0 change
using delegates make it easier. and yes we do need those kinds of stuffs to make code clearer and faster to developp.
Thanks all!!
I know this is asked before, but I can't seem to figure it out.
I have a class which makes a list from a datagridview. I want to do stuff with this list in another class but I cant't access it. I can access it from Form1.cs like the code underneath. How do I access the list from a random class like I can in Form1.cs?
//Opens the file dialog and assigns file path to Textbox
OpenFileDialog browseButton = new OpenFileDialog();
private void browse_Click(object sender, EventArgs e)
{
browseButton.Filter = "Excel Files |*.xlsx;*.xls;*.xlsm;*.csv";
if (browseButton.ShowDialog() == DialogResult.OK)
{
ExcelPath.Text = browseButton.FileName;
fileExcel = ExcelPath.Text;
//SetAttributeValue(ExcelPath, fileExcel);
//nylp();
/*
////IMPORTERER 10TAB-DATA FRA EXCEL TIL DATAGRIDVIEW////
tenTabLine.fileExcel = fileExcel;
tenTabLine.tenTab(tenTabDgv);
*/
////IMPORTERER NYLPDATA TIL DATAGRIDVIEW////
nylpLine.fileExcel = fileExcel;
nylpLine.nylpData(nylpDgv);
////TAR DATA I NYLPDGV DATAGRIDVIEW OG BEREGNER VERTIKALE ELEMENTER////
vertElementer.vertBueDGV(nylpDgv, vertElementerDgv);
GetVertElementasList getList = new GetVertElementasList();
var TEST = getList.vertList(vertElementerDgv);
MessageBox.Show(TEST[5].p2.ToString());
}
else return;
}
When I try to do something like this I get lot of errors in Error List:
class GetKoord
{
GetVertElementasList getList = new GetVertElementasList();
var TEST = getList.vertList(vertElementerDgv);
MessageBox.Show(TEST[5].p2.ToString());
}
This is my list class
class GetVertElementasList
{
private List<vertEl> vertElementList = new List<vertEl>();
public List<vertEl> vertList(DataGridView VertElementer)
{
for (int i = 0; i<VertElementer.Rows.Count - 1; i++)
{
vertElementList.Add(new vertEl
{
elNr = (int)VertElementer.Rows[i].Cells[0].Value,
p1 = (double)VertElementer.Rows[i].Cells[1].Value,
p2 = (double)VertElementer.Rows[i].Cells[2].Value,
z1 = (double)VertElementer.Rows[i].Cells[3].Value,
z2 = (double)VertElementer.Rows[i].Cells[4].Value,
heln1 = Convert.ToDouble(VertElementer.Rows[i].Cells[5].Value),
heln2 = (double)VertElementer.Rows[i].Cells[6].Value
});
}
return vertElementList;
}
}
public class vertEl
{
private int _elNr;
private double _p1;
private double _p2;
private double _z1;
private double _z2;
private double _nylpRad;
private double _heln1;
private double _heln2;
public int elNr
{
get { return _elNr; }
set { _elNr = value; }
}
public double p1
{
get { return _p1; }
set { _p1 = value; }
}
public double p2
{
get { return _p2; }
set { _p2 = value; }
}
public double z1
{
get { return _z1; }
set { _z1 = value; }
}
public double z2
{
get { return _z2; }
set { _z2 = value; }
}
public double nylpRad
{
get { return _nylpRad; }
set { _nylpRad = value; }
}
public double heln1
{
get { return _heln1; }
set { _heln1 = value; }
}
public double heln2
{
get { return _heln2; }
set { _heln2 = value; }
}
}
EDIT:
I've made it work now except that I get a out of range exception.
class code is:
class GetKoord
{
public GetVertElementasList getList = new GetVertElementasList();
BridgGeometry obj = new BridgGeometry();
public void foo()
{
var TEST = getList.vertList(obj.vertElementerDgv);
MessageBox.Show(TEST[2].elNr.ToString());
}
}
In form1 or BridgGeometry as it is called in my project I have which is giving me out of range exception.
GetKoord getZ = new GetKoord();
getZ.foo();
EDIT2:
The code underneath works and gives a message box with some value in list. But the method foo() in class above gives a out of range error.
private void browse_Click(object sender, EventArgs e)
{
browseButton.Filter = "Excel Files |*.xlsx;*.xls;*.xlsm;*.csv";
if (browseButton.ShowDialog() == DialogResult.OK)
{
////TESTING////WORKING CODE AND GIVES A MESSAGEBOX WITH VALUE
GetVertElementasList getVertList = new GetVertElementasList();
var TEST = getVertList.vertList(vertElementerDgv);
MessageBox.Show(TEST[2].elNr.ToString());
}
else return;
}
I think you are trying to access the variable directly in the class; which will not work. Try following
class GetKoord
{
GetVertElementasList getList = new GetVertElementasList();
public void foo()
{
var TEST = getList.vertList(vertElementerDgv);
MessageBox.Show(TEST[5].p2.ToString());
}
}
I tested your code and it seemed to worked. My code for you and #Anand
No Errors, except for empty Lists. But thats because I didn't fed it any information. So, there shouldn't be a problem.
#Grohl maybe try my code and comment where the error is displayed. This should be the most easy way to find the problem.
TestClass which represents class GetKoord
namespace TestForm
{
class TestClass
{
public TestClass()
{
DataGridView tmp = new DataGridView();
GetVertElementasList getList = new GetVertElementasList();
var TEST = getList.vertList(tmp);
MessageBox.Show(TEST[5].p2.ToString());
}
}
}
The GetVertElementasList
namespace TestForm
{
class GetVertElementasList
{
private List<vertEl> vertElementList = new List<vertEl>();
public List<vertEl> vertList(DataGridView VertElementer)
{
for (int i = 0; i < VertElementer.Rows.Count - 1; i++)
{
vertElementList.Add(new vertEl
{
elNr = (int)VertElementer.Rows[i].Cells[0].Value,
p1 = (double)VertElementer.Rows[i].Cells[1].Value,
p2 = (double)VertElementer.Rows[i].Cells[2].Value,
z1 = (double)VertElementer.Rows[i].Cells[3].Value,
z2 = (double)VertElementer.Rows[i].Cells[4].Value,
heln1 = Convert.ToDouble(VertElementer.Rows[i].Cells[5].Value),
heln2 = (double)VertElementer.Rows[i].Cells[6].Value
});
}
return vertElementList;
}
}
//Some other stuff
}
Last but not least. the code from the button click event:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void simpleButton1_Click(object sender, EventArgs e)
{
DataGridView tmp = new DataGridView();
GetVertElementasList getList = new GetVertElementasList();
var TEST = getList.vertList(tmp);
MessageBox.Show(TEST[5].p2.ToString());
TestClass tmpClass = new TestClass();
}
}
To #Grohl EDIT2:
It hurts to see that you are trying to read data without checking if there is any. In such cases, check!
Like this:
if(TEST.Count() >= 3)
{
MessageBox.Show(TEST[2].elNr.ToString());
}
It should debug at be smooth at runtime. I think your problem is getting the data.
Make sure you load the needed data and check if it isn't null.
enter image description here
Ok i need little help with this project. This is my main windows in widows Form
and this is code from MainForm:
using System;
using System.Windows.Forms;
namespace TestNiCat1
{
public partial class Form1 : Form
{
private Atleticar atleticar;
public Atleticar noviAtleticar { get { return atleticar; } }
public string tipDiscipline;
private string imeDiscipline { get; set; }
private int brojUcesnika { get; set; }
public string [] nizUcesnika { get; set; }
public string[] getskakac()
{
string[] arr = new string[listBox1.Items.Count];
for (int i = 0; i < listBox1.Items.Count; i++)
{
arr[i] = listBox1.Items[i].ToString();
}
return arr;
}
//listBox2.trkac to array
public string[] getTrkac()
{
string[] arr1 = new string[listBox2.Items.Count];
for (int i = 0; i < listBox1.Items.Count; i++)
{
arr1[i] = listBox2.Items[i].ToString();
}
return arr1;
}
public Form1()
{
InitializeComponent();
}
private void buttonDodaj_Click(object sender, EventArgs e)
{
if (radioButtonSkok.Checked)
{
atleticar = new Skakac(textBoxIme.Text,textBoxPrezime.Text,float.Parse(textBoxRezultat.Text));
this.listBox1.Items.Add(atleticar);
}
else if (radioButtonPrepone.Checked)
{
atleticar = new Trkac(textBoxIme.Text, textBoxPrezime.Text, float.Parse(textBoxRezultat.Text));
this.listBox2.Items.Add(atleticar);
}
}
private void buttonTrazi_Click(object sender, EventArgs e)
{
if (radioButtonSkok.Checked)
{
getskakac();
}
else if (radioButtonPrepone.Checked)
{
getTrkac();
}
}
}
}
i have 1 abstract class and 2 classes code :
namespace TestNiCat1
{
public abstract class Atleticar
{
protected string ime { get; set; }
protected string prezime { get; set; }
protected float rezultat { get; set; }
public override string ToString()
{
return ime + " " + prezime + " " + rezultat;
} }//abstract Atleticar
public class Skakac : Atleticar
{
private String tip;
public Skakac(String ime,String prezime,float rezultat)
{
this.rezultat = rezultat;
this.ime = ime;
this.prezime = prezime;
}
}public class Trkac : Atleticar
{
public Trkac(String ime,String prezime,float rezultat)
{
this.rezultat = rezultat;
this.ime = ime;
this.prezime = prezime;
}
}
}
what i need is to List all items when pressed Trazi button that will be stored into Listbox1 or listbox2 and sort them by highest result stored.
I made when i press trazi button to store all listbox items into String Array but i need help hot to sort them by highest score and show them into new messageBox OR if there is a way to sort items in listBox immidiatly as they been made in listbox by highest number.
I think this is what you look for
public string[] getskakac()
{
listBox1.Sorted = true;
return listBox1.Items.Cast<string>().ToArray();
}
It appears you may be better off having your abstract class Atleticar implement an IComparable interface. This will make sorting much easier and give you complete control over how Atleticar objects are sorted.
First you need to indicate that the Atleticar class will implement a CompareTo method for sorting:
public abstract class Atleticar : IComparable
Below is the CompareTo method needed when you implement the IComparable interface. I simply compare each object based on the rezultat variable but you can customize this to sort on another variable(s) if needed.
public int CompareTo(object obj) {
Atleticar other = (Atleticar)obj;
if (this.rezultat == other.rezultat)
return 0;
if (this.rezultat > other.rezultat)
return 1;
else
return -1;
}
Below I created a form with a ListBox and two buttons. One button fills the list box with some unsorted Atleticar objects. Button two sorts the list. I do not think you can directly sort the listbox1.Items so I created a list of Atleticar objects from the list box items and then sorted it, cleared the list box items then update it with the sorted data.
private List<Atleticar> GetData() {
List<Atleticar> list = new List<Atleticar>();
Atleticar atl = new Trkac("textBoxIme.Text1", "textBoxPrezime.Text1", 12);
list.Add(atl);
atl = new Trkac("textBoxIme.Text2", "textBoxPrezime.Text2", 1);
list.Add(atl);
atl = new Trkac("textBoxIme.Text3", "textBoxPrezime.Text3", 122);
list.Add(atl);
atl = new Trkac("textBoxIme.Text4", "textBoxPrezime.Text4", 99);
list.Add(atl);
atl = new Trkac("textBoxIme.Text5", "textBoxPrezime.Text5", 03);
list.Add(atl);
atl = new Trkac("textBoxIme.Text6", "textBoxPrezime.Text6", 67);
list.Add(atl);
atl = new Trkac("textBoxIme.Text7", "textBoxPrezime.Text7", -12);
list.Add(atl);
return list;
}
private void buttonGetData_Click(object sender, EventArgs e) {
listBox1.Items.Clear();
foreach (Atleticar a in GetData()) {
listBox1.Items.Add(a);
}
}
private void buttonSort_Click(object sender, EventArgs e) {
List<Atleticar> list = new List<Atleticar>();
foreach (Atleticar a in listBox1.Items) {
list.Add(a);
}
list.Sort();
listBox1.Items.Clear();
foreach (Atleticar a in list) {
listBox1.Items.Add(a);
}
}
Hope this makes sense.
How can I implement in richTextBox something like filter (connected e.g. with combobox) that'll be responsible for showing only lines containing selected word (filters)?
I'm not talking about removing other lines - only "hide".
Is it possible?
Eventually I could use another type control, but if it's not neccessary I'd like to use richTextBox.
I thought now, about storing data in some structure, and make filtering based on this used structure. But don't know if it's efficient solution.
Try to make something like this
public string[] RtbFullText;
private void button7_Click(object sender, EventArgs e)
{
RtbFullText = richTextBox1.Text.Split('\n');
}
private void button8_Click(object sender, EventArgs e)
{
//Filter
richTextBox1.Text = "";
foreach (string _s in RtbFullText)
{
if (_s.Contains("Filter"))
richTextBox1.Text += _s + "\n";
}
}
So you can do this
public class NewRichTextBox : RichTextBox
{
public string[] TotalText;
private bool filter = false;
protected override void OnTextChanged(EventArgs e)
{
base.OnTextChanged(e);
if (!filter)
TotalText = Text.Split('\n');
}
public void Filter(string sf)
{
filter = true;
Text = "";
foreach (string _s in TotalText)
{
if (_s.Contains(sf))
Text += _s + "\n";
}
filter = false;
}
}
public Form1()
{
InitializeComponent();
NewRichTextBox myrtb = new NewRichTextBox();
myrtb.Name = "NRTB";
Controls.Add(myrtb);
}
private void button1_Click(object sender, EventArgs e)
{
NewRichTextBox mtrb = (NewRichTextBox)Controls.Find("NRTB", false)[0];
mtrb.Filter("Filter");
}
OMG i do it, use this class:
public class ListWithRTB : IList
{
private List<string> _contents = new List<string>();
private int _count;
string lastsearch = "";
public ListWithRTB()
{
_count = 0;
}
public object rtb;
private void UpdateRtb(string search)
{
lastsearch = search;
if (rtb is RichTextBox)
{
((RichTextBox)rtb).Text = "";
List<string> help_contents;
if (search != "")
help_contents = _contents.Where(s => s.Contains(search)).ToList();
else
help_contents = _contents;
for (int i = 0; i < help_contents.Count; i++)
{
((RichTextBox)rtb).Text += help_contents[i] + "\n";
}
}
}
public void Filter(string search)
{
UpdateRtb(search);
}
public int Add(object value)
{
if (_count < _contents.Count + 1)
{
_contents.Add((string)value);
_count++;
UpdateRtb(lastsearch);
return (_count);
}
else
{
return -1;
}
}
public void RemoveAt(int index)
{
_contents.RemoveAt(index);
_count--;
UpdateRtb(lastsearch);
}
public void Clear()
{
_contents.Clear();
UpdateRtb(lastsearch);
_count = 0;
}
public bool Contains(object value)
{
return _contents.Contains((string)value);
}
public int IndexOf(object value)
{
return _contents.IndexOf((string)value);
}
public void Insert(int index, object value)
{
_contents.Insert(index,(string) value);
_count++;
}
public bool IsFixedSize
{
get
{
return false;
}
}
public bool IsReadOnly
{
get
{
return false;
}
}
public void Remove(object value)
{
RemoveAt(IndexOf(value));
}
public object this[int index]
{
get
{
return _contents[index];
}
set
{
_contents[index] = value.ToString();
}
}
public void CopyTo(Array array, int index)
{
int j = index;
for (int i = 0; i < Count; i++)
{
array.SetValue(_contents[i], j);
j++;
}
}
public int Count
{
get
{
return _count;
}
}
public bool IsSynchronized
{
get
{
return false;
}
}
public object SyncRoot
{
get
{
return this;
}
}
public IEnumerator GetEnumerator()
{
throw new Exception("The method or operation is not implemented.");
}
public void PrintContents()
{
Console.WriteLine("List has a capacity of {0} and currently has {1} elements.", _contents.Count, _count);
Console.Write("List contents:");
for (int i = 0; i < Count; i++)
{
Console.Write(" {0}", _contents[i]);
}
Console.WriteLine();
}
}
And this how you can use it
ListWithRTB _mlrtb = new ListWithRTB();
private void button1_Click(object sender, EventArgs e)
{
_mlrtb.rtb = richTextBox1;
_mlrtb.Add("Filter");
_mlrtb.Add("123");
_mlrtb.Add("111 Filter");
}
private void button2_Click(object sender, EventArgs e)
{
_mlrtb.Filter("Filter");
}
private void button3_Click(object sender, EventArgs e)
{
_mlrtb.Filter("");
}
private void Button_Click(object sender, RoutedEventArgs e)
{
if (!string.IsNullOrEmpty(SearchableString) && !string.IsNullOrEmpty(FullRichtxt))
{
var SplitedTxt = FullRichtxt.Split('\n').ToList<string>();
List<string> filterlist = SplitedTxt.Where(x => x.Contains(contx.SearchableString)).ToList<string>();
string FilterString=string.Empty;
foreach(string str in filterlist)
{
FilterString+=str+"\n";
}
(RichTextBox1 as RichTextBox).AppendText(FilterString);
}
}
I know this has been a very old question however I ran into the same issue and implemented it which also retains any RTF formatting.
/// <summary>
/// This Control allows to filter the content of the RichTextBox by either manually
/// calling <c>ApplyFilter(string)</c> with the search string or specifying a TextBox Control
/// as a filter reference.
///
/// Matching lines will be retained, other will be deleted.
///
/// Retains RTF formatting and when removing the filter restores the original content.
///
/// Ideal for a Debug Console.
///
/// </summary>
public class RichFilterableTextBox : RichTextBox
{
private Timer timer;
private string OriginalRTF = null;
private TextBox _filterReference;
private int _interval = 2000;
public TextBox FilterReference
{
get => _filterReference;
set
{
//if we had already a filter reference
if (_filterReference != null)
{
//we should remove the event
_filterReference.TextChanged -= FilterChanged;
}
_filterReference = value;
//if our new filter reference is not null we need to register our event
if (_filterReference != null)
_filterReference.TextChanged += FilterChanged;
}
}
/// <summary>
/// After the filter has been entered into the FilerReference TextBox
/// this will auto apply the filter once the interval has been passed.
/// </summary>
public int Interval
{
get => _interval;
set
{
_interval = value;
timer.Interval = Interval;
}
}
public RichFilterableTextBox()
{
timer = new Timer();
timer.Interval = Interval;
timer.Tick += TimerIntervalTrigger;
}
public void SetFilterControl(TextBox textbox)
{
this.FilterReference = textbox;
}
public void ApplyFilter(string searchstring)
{
int startIndex = 0;
int offset = 0;
//check each line
foreach (var line in this.Lines)
{
offset = 0;
SelectionStart = startIndex + offset;
SelectionLength = line.Length + 1;
//if our line contains our search string/filter
if (line.Contains(searchstring))
{
//we apply an offset based on the line length
offset = line.Length;
}
else
{
//otherwise delete the line
SelectedText = "";
}
//move the start index forward based on the current selected text
startIndex += this.SelectedText.Length;
}
}
private void FilterChanged(object sender, EventArgs e)
{
//take snapshot of original
if (OriginalRTF == null)
{
OriginalRTF = this.Rtf;
}
else
{
//restore original
Rtf = OriginalRTF;
OriginalRTF = null;
}
timer.Stop();
timer.Start();
}
private void TimerIntervalTrigger(object sender, EventArgs e)
{
//stop the timer to avoid multiple triggers
timer.Stop();
//apply the filter
ApplyFilter(FilterReference.Text);
}
protected override void Dispose(bool disposing)
{
timer.Stop();
timer.Dispose();
base.Dispose(disposing);
}
}
This control can be either used standalone and be filter by calling the method
ApplyFilter(string searchString) with the desired search string. Or it can be connected to a TextBox
where you will be able to enter the phrase in. After a set timer interval it will auto trigger the filtering.
I am using this as a Log Display during runtime where I am also applying color codes to severity and my goal was to retain the formatting as well as be able to quickly search/filter. I attached a few screenshots:
There is still room for improvements and I hope this can be used as a starting code base.