2012-12-03 65 views
0

這是爲我正在爲課程做的項目,我試圖創建一個有2個按鈕的勝利表單,當按鈕在文本框中遞增時被按下,當按下不同的按鈕時,按鈕會減少。我無法找到符合要求的正確路線。有人可以幫助我嗎?button push increment number to a text box c#winform

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) 
      { 

      } 
     } 
    } 

回答

4

由於它是一個類項目,我只能給你一個提示。

您需要定義變量i以外的按鈕點擊事件。在兩個事件中使用相同的變量。

而且看difference between i++ and ++i

+0

只是爲了增加提示,全局思考。 – Mataniko

0

聲明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; 
    } 
} 
+0

謝謝你,現在它的工作! – CaptainTeancum