如何在c#中添加两个数字 [英] how to add two numbers in c#

查看:83
本文介绍了如何在c#中添加两个数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好我正在使用c#.net窗口应用程序



i无法添加两个数字



Hi i am working on c# .net window application

i am unable to add two numbers

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace Add
{
    public partial class calci : Form
    {
        public calci()
        {
            InitializeComponent();
        }

        private void But_Add_Click(object sender, EventArgs e)
        {
          int a = Convert.ToInt32(Txt_1.Text );
          int b = Convert.ToInt32(Txt_2.Text);

            Ans.Text = a + b;
           

        }

    }
}





添加了代码块 - OriginalGriff [/ edit]



[edit]Code block added - OriginalGriff[/edit]

推荐答案

这完全取决于用户在文本框中输入的内容。如果他键入了一些无效字符,那么该代码将无效。您还需要将您的号码转换为字符串才能显示它!

试试这个:
It's all going to depend on what your user types into the text boxes. If he types some invalid characters, then that code will not work. You also need to convert your number to a string in order to display it!
Try this:
private void butAdd_Click(object sender, EventArgs e)
    {
    int a;
    int b;
    if (!int.TryParse(tbFirstNumber.Text, out a))
        {
        MessageBox.Show("I need just a number in the first box!");
        return;
        }
    if (!int.TryParse(tbSecondNumber.Text, out b))
        {
        MessageBox.Show("I need just a number in the second box!");
        return;
        }
    labAnswer.Text = (a + b).ToString();
    }


您可以在文档 [ ^ ], Convert.ToInt32 方法可能会抛出异常,因此您,正如明智的开发人员应该在您的代码中处理的那样这种可能性。请参阅文档中的示例代码。
As you may easily find in the documentation[^], Convert.ToInt32 method may throw exceptions, hence you, as the wise developer should handle in your code such a possibility. See the sample code in the documentation.


Windows窗体中有一个名为NumericUpDown的控件。看看那个。它将为您节省开销,如转换和验证。
There is a control called NumericUpDown for Windows forms. Have a look at that. It will save you from overhead like conversion and validations.


这篇关于如何在c#中添加两个数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆