本文介绍如何在VisualStudio中创建用户控件显示下拉计算器,弹出效果类似于日历控件。介绍如果我们在做一个像库存控制和计费系统这样的项目,某些部分可能需要手动计算值。因此,用户必须使用计算器得到结果,然后将其填入输入字段,或者在工作窗口上单独打开一个计算器窗口。总而言之,不便和麻烦。本文主要介绍如何在DataGridView单元格中添加下拉计算器,如下图所示:使用代码第一步,我们首先要创建一个函数计算器,并能够使用控件。因此,您不妨先创建一个VisualStudio用户自定义控件。怎么做?打开VS,新建一个WindowsForms应用程序(即使你在当前项目中也可以这样做,但最好先分离再组合)。然后,在解决方案资源管理器中,右键单击该项目,选择添加->用户控件。为其命名(此处使用“CalculatorControl”),然后添加它。这将为您提供一个类似于工作区的Windows窗体。在其顶部,使用控件工具箱中的TextBox和Button创建一个计算器布局。布局越小越好(想想日历控件),因为这只是一个计算器。为了快速获得计算器功能,可以点击这里下载NCal(一定要下载二进制文件),添加到项目的参考文件中。实现每个数字按钮的点击事件,将对应的数字输入/(追加)到文本框中,然后以同样的方式实现其他按钮,如+、X、/……并输入/(追加)对应的符号要在文本框中...例如在文本框中输入:2*3+4然后使用下面的代码验证表达式并得到结果://usingSystem.Windows.Forms;usingNCalc;//stringresText;booleqPressed;doubleresult;publicvoidbtnEqual_Click(objectsender,EventArgse){Expressionex=newExpression(textBox1.Text);if(ex.HasErrors()){//InvalidExpression}else{result=Convert.ToDouble(ex.Evaluate());resText=result.ToString();}textBox1.Text=resText;text=resText;eqPressed=true;}//至此计算器功能已经完成。直接构建解决方案,然后你会发现用户控件显示在工具箱的顶部。您可以添加Windows窗体,将用户控件拖放到窗体中并运行它以查看它是否有效。然后,在要添加下拉计算器的项目中,创建另一个只有一个小按钮的用户控件。此按钮将用于打开计算器。将CalculatorControl内置参考文件添加到项目中。新建一个继承ToolStripDropDown的类:usingSystem.Windows.Forms;classCalDrop:ToolStripDropDown{Controlcontent;ToolStripControlHostdrop;publicCalDrop(CalculatorControlcontent){this.content=content;this.drop=newSystem.Windows.Forms.ToolStripControlHost(content);//Addthehosttothelistthis.Items.Add(this.drop);}}在按钮的点击事件中添加如下代码:(button1.Location);PointrelativeLoc=newPoint(controlLoc.X+button1.Width+100,controlLoc.Y+button1.Height*2);RectanglecalRect=button1.DisplayRectangle;cal.Show(locPoint);}在DataGridViewCell中添加控件构建解决方案时,工具箱中会出现一个新的按钮控件。将以下代码添加到项目的Form类中。私人计算器选择计算器;publicform1(){calculator=newCalculatorPick();calculator.Visible=false;dataGridView2.Controls.Add(calculator);}privatevoiddataGridView2_CellClick(objectsender,DataGridViewCellEventArgse){if(e.ColumnIndex==clmCommisionectRangdex=GridView=GridView).GetCellDisplayRectangle(e.ColumnIndex,e.RowIndex,false);Pointp=calculator.FindForm().PointToClient(calculator.Parent.PointToScreen(calculator.Location));p.X-=calculator.Width/3;p.Y+=calculator.Height;计算器.LocPoint=p;calculator.Width=calRect.Width/3;calculator.Height=calRect.Height;calculator.Visible=true;calculator.Calculator.btnEqual.Click+=newEventHandler(calculatorBtnEqlClicked);}elseif(calculator!=null)calculator.Visible=false;}voidcalculatorBtnEqlClicked(objectsender,EventArgse){dataGridView2.CurrentCell.Value=calculator.Calculator.Result.ToString();}兴趣点这项技术描述了向DataGridView添加控件,让界面看起来更具交互性。许可证本文中的任何相关源代码和文档均已获得代码项目开放许可证(CPOL)的许可。
