计算器总计失败

时间:2014-02-21 05:28:43

标签: c# wpf

我正在使用C#编写计算器。

namespace Calculator
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }
        public void Total(string num)   
        {
            lblTotal.Content = Convert.ToString(lblTotal.Content) + num;
        }
        private void one_Click(object sender, RoutedEventArgs e)
        {
            Total( Convert.ToString(1) );
        }
        private void two_Click(object sender, RoutedEventArgs e)
        {
            Total( Convert.ToString(2) );
        }
        private void three_Click(object sender, RoutedEventArgs e)
        {
            Total( Convert.ToString(3) );
        }
        private void four_Click(object sender, RoutedEventArgs e)
        {
            Total( Convert.ToString(4) );
        }
        private void five_Click(object sender, RoutedEventArgs e)
        {
            Total( Convert.ToString(5) );
        }
        private void six_Click(object sender, RoutedEventArgs e)
        {
            Total( Convert.ToString(6) );
        }
        private void seven_Click(object sender, RoutedEventArgs e)
        {
            Total( Convert.ToString(7) );
        }
        private void eight_Click(object sender, RoutedEventArgs e)
        {
            Total( Convert.ToString(8) );
        }
        private void nine_Click(object sender, RoutedEventArgs e)
        {
            Total( Convert.ToString(9) );
        }
        private void ten_Click(object sender, RoutedEventArgs e)
        {
            Total( Convert.ToString(10) );
        }
        private void zero_Click(object sender, RoutedEventArgs e)
        {
            Total( Convert.ToString(0) );
        }

        private void add_Click(object sender, RoutedEventArgs e)
        {
            Total("+");
        }

        private void subtract_Click(object sender, RoutedEventArgs e)
        {
            Total("-");
        }

        private void multiply_Click(object sender, RoutedEventArgs e)
        {
            Total("*");
        }

        private void divide_Click(object sender, RoutedEventArgs e)
        {
            Total("/");
        }

        private void total_Click(object sender, RoutedEventArgs e)
        {
            int calculate;
            string content;

            content = Convert.ToString(lblTotal.Content);
            calculate = Convert.ToInt32(content);

        }

    }

}

因此,当用户单击total按钮时,它应该打开lblTotal.Content并获得计算所需的数学并将lblTotal.Content设置为答案。

我收到此错误:

System.FormatException was unhandled
  _HResult=-2146233033
  _message=Input string was not in a correct format.
  HResult=-2146233033
  IsTransient=false
  Message=Input string was not in a correct format.
  Source=mscorlib
  StackTrace:
       at System.Number.StringToNumber(String str, NumberStyles options, NumberBuffer& number, NumberFormatInfo info, Boolean parseDecimal)
       at System.Number.ParseInt32(String s, NumberStyles style, NumberFormatInfo info)
       at System.String.System.IConvertible.ToInt32(IFormatProvider provider)
       at System.Convert.ToInt32(Object value)
       at Calculator.MainWindow.total_Click(Object sender, RoutedEventArgs e) in c:\Users\Administrator\Documents\Visual Studio 2013\Projects\Calculator\Calculator\MainWindow.xaml.cs:line 100
       at System.Windows.RoutedEventHandlerInfo.InvokeHandler(Object target, RoutedEventArgs routedEventArgs)
       at System.Windows.EventRoute.InvokeHandlersImpl(Object source, RoutedEventArgs args, Boolean reRaised)
       at System.Windows.UIElement.RaiseEventImpl(DependencyObject sender, RoutedEventArgs args)
       at System.Windows.UIElement.RaiseEvent(RoutedEventArgs e)
       at System.Windows.Controls.Primitives.ButtonBase.OnClick()
       at System.Windows.Controls.Button.OnClick()
       at System.Windows.Controls.Primitives.ButtonBase.OnMouseLeftButtonUp(MouseButtonEventArgs e)
       at System.Windows.UIElement.OnMouseLeftButtonUpThunk(Object sender, MouseButtonEventArgs e)
       at System.Windows.Input.MouseButtonEventArgs.InvokeEventHandler(Delegate genericHandler, Object genericTarget)
       at System.Windows.RoutedEventArgs.InvokeHandler(Delegate handler, Object target)
       at System.Windows.RoutedEventHandlerInfo.InvokeHandler(Object target, RoutedEventArgs routedEventArgs)
       at System.Windows.EventRoute.InvokeHandlersImpl(Object source, RoutedEventArgs args, Boolean reRaised)
       at System.Windows.UIElement.ReRaiseEventAs(DependencyObject sender, RoutedEventArgs args, RoutedEvent newEvent)
       at System.Windows.UIElement.OnMouseUpThunk(Object sender, MouseButtonEventArgs e)
       at System.Windows.Input.MouseButtonEventArgs.InvokeEventHandler(Delegate genericHandler, Object genericTarget)
       at System.Windows.RoutedEventArgs.InvokeHandler(Delegate handler, Object target)
       at System.Windows.RoutedEventHandlerInfo.InvokeHandler(Object target, RoutedEventArgs routedEventArgs)
       at System.Windows.EventRoute.InvokeHandlersImpl(Object source, RoutedEventArgs args, Boolean reRaised)
       at System.Windows.UIElement.RaiseEventImpl(DependencyObject sender, RoutedEventArgs args)
       at System.Windows.UIElement.RaiseTrustedEvent(RoutedEventArgs args)
       at System.Windows.UIElement.RaiseEvent(RoutedEventArgs args, Boolean trusted)
       at System.Windows.Input.InputManager.ProcessStagingArea()
       at System.Windows.Input.InputManager.ProcessInput(InputEventArgs input)
       at System.Windows.Input.InputProviderSite.ReportInput(InputReport inputReport)
       at System.Windows.Interop.HwndMouseInputProvider.ReportInput(IntPtr hwnd, InputMode mode, Int32 timestamp, RawMouseActions actions, Int32 x, Int32 y, Int32 wheel)
       at System.Windows.Interop.HwndMouseInputProvider.FilterMessage(IntPtr hwnd, WindowMessage msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
       at System.Windows.Interop.HwndSource.InputFilterMessage(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
       at MS.Win32.HwndWrapper.WndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
       at MS.Win32.HwndSubclass.DispatcherCallbackOperation(Object o)
       at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs)
       at MS.Internal.Threading.ExceptionFilterHelper.TryCatchWhen(Object source, Delegate method, Object args, Int32 numArgs, Delegate catchHandler)
       at System.Windows.Threading.Dispatcher.LegacyInvokeImpl(DispatcherPriority priority, TimeSpan timeout, Delegate method, Object args, Int32 numArgs)
       at MS.Win32.HwndSubclass.SubclassWndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam)
       at MS.Win32.UnsafeNativeMethods.DispatchMessage(MSG& msg)
       at System.Windows.Threading.Dispatcher.PushFrameImpl(DispatcherFrame frame)
       at System.Windows.Threading.Dispatcher.PushFrame(DispatcherFrame frame)
       at System.Windows.Threading.Dispatcher.Run()
       at System.Windows.Application.RunDispatcher(Object ignore)
       at System.Windows.Application.RunInternal(Window window)
       at System.Windows.Application.Run(Window window)
       at System.Windows.Application.Run()
       at Calculator.App.Main() in c:\Users\Administrator\Documents\Visual Studio 2013\Projects\Calculator\Calculator\obj\Debug\App.g.cs:line 0
       at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
       at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
       at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
       at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
       at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       at System.Threading.ThreadHelper.ThreadStart()
  InnerException: 

我希望有一个解决办法。单击总计按钮后,程序崩溃,然后我收到上面的错误。

8 个答案:

答案 0 :(得分:5)

您正尝试使用Convert.ToInt322+5转换为7。这不是Convert.ToInt32所做的。 Convert.ToInt32int.Parse使用表示数字(12345-1245)的字符串并将其转换为整数。

在做其他事情之前,您应该先查看data types

您需要自己解析表达式,或使用表达式解析器。请参阅I need a fast runtime expression parserHow would you create an expression parser in c#?

有关如何在不使用解析表达式的情况下在WPF 中创建计算器的示例,请参阅MSDN Sample calculator

答案 1 :(得分:2)

使用链接中提供的Int32.TryParseMSDN)。

答案 2 :(得分:1)

lblTotal.Content可能是您的问题,因为它可能不是存储为字符串的数字,或者该字符串中可能还有其他字符。

答案 3 :(得分:1)

这应该有效:

        int content;
        if (Int32.TryParse(lblTotal.Content.ToString(), out content))
        {
            int calculate = content;
            lblTotal.Content = calculate;
        }

如果条件为true,则数值将分配给content,然后执行其余方法。

当然,如果您不想在该标签内进行数学运算,那当然就是这样。

修改

这篇文章对您非常有帮助:

http://code.msdn.microsoft.com/windowsdesktop/Simple-Calculator-d1d8cf4c/view/SourceCode#content

点击浏览代码标签,查看代码。

答案 4 :(得分:1)

private void total_Click(object sender, RoutedEventArgs e)
{
    int content ;
    int.TryParse(convert.ToString(lblTotal.Content), out content );
    int calculate = content;
    lblTotal.Content =convert.ToString( calculate);
}

答案 5 :(得分:1)

来自你的电话堆栈,     在System.Convert.ToInt32(对象值)。 它似乎说你的Convert.ToInt32的输入类型是不对的。我不确定你的lblTotal.Content的类型,因为你不在这里放相关的代码,但我想它可能不是字符串,你能看一下吗?我想如果lblTotal.Content是一个容器,它应该像lblTotal.Content.Text一样使用......

答案 6 :(得分:1)

这应该给你一个提示:输入字符串的格式不正确。

从字符串到int的转换失败了。使用Int32.TryParse或为代码添加一些异常处理:

int calculate;
int content;

if (Int32.TryParse(lblTotal.Content, out content))
{
    calculate = content;
    lblTotal.Content = calculate.ToString();
}
else
{
    lblTotal.Content = String.Format("Error converting {0}", lblTotal.Content);
}

上面的代码在这方面完全没有任何意义,顺便说一下,你获取lblTotal的内容,将其转换为int,将其分配给calculate并将lblTotal的内容设置为相同的值。

答案 7 :(得分:1)

如何获取标签的Content属性。对于Lablel,内容属性不在win表单中。

如果可用于u,则使用ToString()函数将字符串值分配给Content。

private void total_Click(object sender,RoutedEventArgs e) {

lblTotal.Content=Convert.ToInt32(lblTotal.Content).ToString();

}