1

I am coding a calculator using 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);

        }

    }

}

So when a user clicks the total button, it should open the lblTotal.Content and get the math it needs to calculate and set the lblTotal.Content to the answer.

I get this error:

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: 

I hope there is a fix. As soon as I click the total button, the program crashes and then I get the error above.

Selman Genç
  • 100,147
  • 13
  • 119
  • 184
Hassan
  • 111
  • 10

8 Answers8

5

You are trying to use Convert.ToInt32 to convert 2+5 to 7. That is not what Convert.ToInt32 does. Convert.ToInt32 and int.Parse take a string representing a number (12345 or -1245) and convert it to an integer.

You should probably look at data types before doing anything else.

You will need to parse the expression yourself, or use an expression parser. see I need a fast runtime expression parser or How would you create an expression parser in c#?

For an example of how to make a calculator in WPF without parsing expressions, see the MSDN Sample calculator.

Community
  • 1
  • 1
Mitch
  • 21,223
  • 6
  • 63
  • 86
  • This is probably the most relevant answer out of all (including mine). He's trying to do math in that label. – B.K. Feb 21 '14 at 05:57
  • I am a newbie to C# and I am trying to learn stuff, help would be much appreciated! – Hassan Feb 21 '14 at 05:58
  • @Hassan, Did you read the articles I linked to? Parsing expressions is not a 5 line operation... – Mitch Feb 21 '14 at 05:59
  • @Hassan We understand that you're new. Start small. By looking at your updated code above, you need to start out small and get to know data types, as Mitch has mentioned; and basic methods applicable to them. You're trying to do too many things at once here, which will cause you more confusion. – B.K. Feb 21 '14 at 06:02
  • @Hassan since you are stating that you are just starting out in c#, this is equivalent of jumping into the deep end of the pool without knowing how to swim, this is a very non standard way of creating a calculator, try to imagine what happens when you use an actual calculator and try to emulate it. – Mark Hall Feb 21 '14 at 06:04
  • Er, i have no idea what else to do.. lol.. I did start small, and so far all went right, I even made another calculator. It was with variables, i think I should make this in the same way like the previous one, the previous one just defined the variables and calculated in the equation: num1 + num2 - num3 * num4 – Hassan Feb 21 '14 at 06:05
  • @Hassan, it is a sample. Go through it till you understand it, then you will know how to do what you need with your project. Of key importance is the codebehind of `Window1.xaml`, where they implement the calculator. `Calc(Operation op)` to be specific (line 317). – Mitch Feb 21 '14 at 06:09
  • @Hassan Check out my answer for a quick update. See if that helps you. – B.K. Feb 21 '14 at 06:10
2

Use Int32.TryParse (MSDN) as given in the link.

Babu James
  • 2,740
  • 4
  • 33
  • 50
1

lblTotal.Content is likely your problem, as it is probably not a number stored as a string, or there could be other characters within that string.

panoptical
  • 782
  • 1
  • 8
  • 22
1

This should work:

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

If condition is true, numerical value will be assigned to content and then the rest of your method executes.

That's of course if you're not trying to do your math within that label.

EDIT:

Here's an article that will be very helpful to you:

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

Click on Browse Code tab and look through the code.

B.K.
  • 9,982
  • 10
  • 73
  • 105
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);
}
  • Error 1 The best overloaded method match for 'int.TryParse(string, out int)' has some invalid arguments c:\users\administrator\documents\visual studio 2013\projects\calculator\calculator\mainwindow.xaml.cs 99 13 Calculator – Hassan Feb 21 '14 at 05:37
1

From your call stack here, at System.Convert.ToInt32(Object value). it seems to say your input type to Convert.ToInt32 is not right. I am not sure about your type of lblTotal.Content as you don't put related code here, but I guess it may be not string, Could you take a look at that ? I guess if lblTotal.Content is a container, it should use sth like lblTotal.Content.Text

linpingta
  • 2,324
  • 2
  • 18
  • 36
  • I am not using cmd line to use 'System.' – Hassan Feb 21 '14 at 05:43
  • @Hassan System is namespace in C# and I think from call stack it means your input of ToInt32 function is not right. A little confused, please tell me the solution when you finish, thx. – linpingta Feb 21 '14 at 07:48
1

This should give you a hint: Input string was not in a correct format.

It's the conversion from string to int that fails. Use Int32.TryParse or add some exception handling to your code:

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);
}

The above code does exactly nothing in this for, by the way, you take the content of lblTotal, convert it to int, assign it to calculate and the set the content of lblTotal to the same value.

Håkan Fahlstedt
  • 2,040
  • 13
  • 17
1

How you are able to getting Content property for label. For Lablel content property is not there in win forms.

if it is available for u then assign string value to Content using ToString() function.

private void total_Click(object sender, RoutedEventArgs e) {

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

}

Guna
  • 21
  • 4