计算数字数 c#

本文关键字:数字 计算 | 更新日期: 2023-09-27 18:30:23

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

    }
}

计算数字数 c#

您需要

处理表单的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());
}