【问题标题】:button push increment number to a text box c# winform按钮将增量数字推送到文本框 c# winform
【发布时间】:2012-12-03 05:15:03
【问题描述】:

这是针对我正在为班级做的一个项目,我正在尝试创建一个具有 2 个按钮的 win 表单,其中一个按钮在按下按钮时会在文本框中增加,另一个按钮在按下按钮时会减少按钮被按下。我很难找到合适的线路来做我想做的事。有没有人可以帮帮我?

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

    namespace Project10TC
    {
        public partial class Form1 : Form


        {
            public Form1()
            {
                InitializeComponent();
            }

            private void exitToolStripMenuItem1_Click(object sender, EventArgs e)
            {
                this.Close();
            }

            private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
            {
                MessageBox.Show("Teancum Project 10");
            }

            private void button1_Click(object sender, EventArgs e)
            {
                 int i = 1;

                textBox1.Text = Convert.ToString(i++);
            }

            private void button2_Click(object sender, EventArgs e)
            {
                 int i = 1;

                textBox1.Text = Convert.ToString(i--);
            }

            private void button3_Click(object sender, EventArgs e)
            {
                textBox1.Clear();
            }

            private void textBox1_TextChanged(object sender, EventArgs e)
            {

            }
        }
    }

【问题讨论】:

    标签: c# winforms


    【解决方案1】:

    既然是课堂项目,我只能给你一个提示。

    您需要在按钮点击事件之外定义变量i。在两个事件中使用相同的变量。

    另请查看difference between i++ and ++i

    【讨论】:

    • 只是为了添加提示,全局思考。
    【解决方案2】:

    i 变量声明为字段。此外,我会使用++i 而不是i++。否则,您在文本框和变量中有不同的值。另外,不需要使用Convert.ToString()

    public partial class Form1 : Form
    {
        int i;
    
        public Form1()
        {
            InitializeComponent();
            i = 0;
        }
    
        //...
    
        private void button1_Click(object sender, EventArgs e)
        {
            textBox1.Text = (++i).ToString();
        }
    
        private void button2_Click(object sender, EventArgs e)
        {
            textBox1.Text = (--i).ToString;
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-01-01
      • 2016-10-28
      • 2021-11-29
      • 2018-11-06
      • 1970-01-01
      • 2021-03-28
      • 2023-03-22
      • 1970-01-01
      相关资源
      最近更新 更多