计算数字c#

时间:2013-09-05 00:37:50

标签: c# winforms numbers

如何编写一个代码,允许我计算放在文本框中的数字的数量。 例如,我有一个表单,一个按钮和一个文本框。我在文本框中输入1;按下按钮。输入3;按下按钮。输入5;按下按钮。当我关闭我的表格时,会出现一个消息框,说我有3个号码。

到目前为止

表单1

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void btnReadings_Click(object sender, EventArgs e)
    {
        using (Form2 f2 = new Form2())
        {
            while (f2.ShowDialog() != DialogResult.OK)
            {
                this.Enabled = false;
            }
            this.Enabled = true;
        }
    }
}

表格2

 public partial class Form2 : Form
{
    public Form2()
    {
        InitializeComponent();
    }

    private void Form2_FormClosing(object sender, FormClosingEventArgs e)
    {
        this.DialogResult = DialogResult.OK;
    }

    private void button1_Click(object sender, EventArgs e)
    {


    }
}

1 个答案:

答案 0 :(得分:1)

您需要处理表单的Closing事件,如下所示:

private void Form1_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
    int countOfNumbers = 0;

    foreach(char c in textBox1.Text)
    {
        if(Char.IsDigit(c))
        {
            countOfNumbers += 1;
        }
    }

    // Display a MsgBox asking the user to save changes or abort. 
    MessageBox.Show("Number of numbers in text box is: " + countOfNumbers.ToString());
}