Click here to Skip to main content
15,880,405 members
Articles / Programming Languages / C#
Tip/Trick

Create a Drop Down Calculator Opens like DateTimePicker

Rate me:
Please Sign up or sign in to vote.
5.00/5 (12 votes)
24 Jun 2015CPOL2 min read 43.9K   21   1
This tip describes creating a user control to display a drop down calculator that pops out like the DateTimePicker in Visual Studio

Introduction

If we are working on a project like an inventory control or a billing system, some sections might have to be equipped with entering manually calculated values. Thus the user will have to use his/her calculator to get the result and put in the input field or put a button to open a calculator window separately over the working window. Thus user can do the calculation and enter the result in the input field keeping the value in mind which makes the user feel inconvenient.

In this tip, it describes to add a drop down calculator to a DataGridView Cell like in the below images:

Before Opening the Drop

Drop View

Using the Code

As the first step, we have to create a functional calculator and it should be able to use a control. So let's create a Visual Studio User Control. For that, open VS and create a new Windows Forms Application (even you can do this in your currently working project but better to do separately and combine. This tip explains everything.).

Then in solution explorer, right click on the project, choose add->User Control. Give a name ("CalculatorControl" is used in here) and add. This gives you a Windows Form like working space. On it, create the layout of a calculator with the TextBox and Button controls in the tool box. Make sure to make it smaller as possible (just think about the DateTimePicker) and this is just the calculator no other.

Calculator Design

To make the calculator functional easily, download the NCal reference from here (Make sure to download the binary) and add to references in our project.

Implement the click events of the number buttons to type/(append) the numbers in the text field (if your design is same as this) and implement the other buttons such as +,X,/.. also to type/(append) the symbol...

Example textBox: 2*3+4

Then, use the following code to verify the expression and get the result:

C#
//
using System.Windows.Forms;
using NCalc;
//
    string resText;
    bool eqPressed;
    double result;

public void btnEqual_Click(object sender, EventArgs e)
        {
            Expression ex = new Expression(textBox1.Text);
            if (ex.HasErrors())
            {
                //Invalid Expression
            }
            else
            {
                result = Convert.ToDouble(ex.Evaluate());
                resText = result.ToString();
            }
            textBox1.Text = resText;
            text = resText;
            eqPressed = true;
                
        }
//

Now the calculator functionality is done. Just build the solution, then you might see in the top of the tool box, your user control is displayed. You can add a Windows Form and drag and drop the User Control to it and run to see whether it's working.

Then in the project which you want to add a drop down calculator, create another user control with just a little button. This button will be used as the control to open the drop down.

Add the reference of the built file of the CalculatorControl to your project.

Create a new class that inherits ToolStripDropDown:

C#
using System.Windows.Forms;

class CalDrop : ToolStripDropDown
    {
      Control content;
      ToolStripControlHost drop;

public CalDrop(CalculatorControl content)
        {
            
            this.content = content;
            
            this.drop= new System.Windows.Forms.ToolStripControlHost(content);
                        

            //Add the host to the list
            this.Items.Add(this.drop);
        }
}

Add the code below to the click event of the button.

C#
private void button1_Click(object sender, EventArgs e)
        {
            CalculatorControl calculator = new CalculatorControl();
            CalDrop cal = new CalDrop(calculator);
            
            
            Point controlLoc = fm.PointToScreen(button1.Location);
            Point relativeLoc = new Point(controlLoc.X + button1.Width + 100, 
				controlLoc.Y + button1.Height * 2);
            Rectangle calRect = button1.DisplayRectangle;
            cal.Show(locPoint);
        }

Adding the Control to DatagridViewCell

When you build the solution, the new button control will appear in the tool box. Add the below code parts to the form class of the project.

C#
private CalculatorPick calculator;

public form1()
{
            calculator = new CalculatorPick();
                        
            calculator.Visible = false;
            dataGridView2.Controls.Add(calculator);
}

private void dataGridView2_CellClick(object sender, DataGridViewCellEventArgs e)
{
                if (e.ColumnIndex == clmCommision.Index)
                {
                    Rectangle calRect = dataGridView2.GetCellDisplayRectangle
						(e.ColumnIndex, e.RowIndex,false);                   

                    Point p = calculator.FindForm().PointToClient
				(calculator.Parent.PointToScreen(calculator.Location));
                    p.X -= calculator.Width/3;
                    p.Y += calculator.Height;
                    calculator.LocPoint = p;  

                    calculator.Width = calRect.Width/3;
                    calculator.Height = calRect.Height;

                    calculator.Visible = true;
                    calculator.Calculator.btnEqual.Click += new EventHandler(calculatorBtnEqlClicked);
                }
                else
                    if(calculator!=null)
                    calculator.Visible = false;
}

void calculatorBtnEqlClicked(object sender, EventArgs e)
{            
            dataGridView2.CurrentCell.Value = calculator.Calculator.Result.ToString();            
}

Points of Interest

This tip describes adding the control to a datagridview but this can be used as you wish to make your interfaces more interactive.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Sri Lanka Sri Lanka
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
Questionthank's Pin
Member 124464206-Jul-18 1:41
professionalMember 124464206-Jul-18 1:41 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.