-4

如何编写代码来计算我在文本框中输入的数字的数量。例如,我有一个表单、一个按钮和一个文本框。我在文本框中输入 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)
    {


    }
}
4

1 回答 1

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());
}
于 2013-09-05T00:45:02.830 回答