2010-09-23 47 views
0

我是C#編程的新手,所以請不要對我太苛刻。我以前用ActionScript編碼過,並且注意到它非常相似。在C#中,如何讓我的按鈕的文本動態?

無論如何,我需要基本上建立一個簡單的應用程序,其中2個字符給對方「錢」...或整數。角色名稱應該是動態的,並且按鈕應該是名稱的名稱。

請幫忙!這是我到目前爲止有:

namespace Lab_2 
{ 
    public partial class Form1 : Form 
    { 
     Guy firstName; 
     Guy secondName; 
     int bank = 100; 

     public Form1() 
     { 
      InitializeComponent(); 

      firstName = new Guy() { Cash = 100, Name = "Joe" }; 
      secondName = new Guy() { Cash = 50, Name = "Bob" }; 

      firstName = textBox1.Text; 
      secondName = textBox2.Text; 

      UpdateForm(); 
     } 

     public void UpdateForm() 
     { 
      name1CashLabel.Text = firstName.Name + " has $" + firstName.Cash; 
      name2CashLabel.Text = secondName.Name + " has $" + secondName.Cash; 
      bankCashLabel.Text = "The bank has $" + bank; 
     } 

     private void button1_Click(object sender, EventArgs e) 
     { 
      button1.Text = "Give $10 to " + firstName.Name; 

      if (bank >= 10) 
      { 
       bank -= firstName.ReceiveCash(10); 
       UpdateForm(); 
      } 
      else 
      { 
       MessageBox.Show("The bank is out of money."); 
      } 
     } 

     private void button2_Click(object sender, EventArgs e) 
     { 
      bank += secondName.GiveCash(5); 
      UpdateForm(); 
     } 

     private void button3_Click(object sender, EventArgs e) 
     { 
      secondName.ReceiveCash(firstName.GiveCash(10)); 
      UpdateForm(); 
     } 

     private void button4_Click(object sender, EventArgs e) 
     { 
      firstName.ReceiveCash(secondName.GiveCash(5)); 
      UpdateForm(); 
     } 

     private void name1_Click(object sender, EventArgs e) 
     { 
      firstName.Name = textBox1.Text; 
     } 
    } 
} 
+1

你什麼時候更新按鈕文字?我不知道你的問題的含義... – froeschli 2010-09-23 04:27:19

+0

鑑於命名空間是這個作業嗎? – 2010-09-23 04:28:29

+1

另外'Name = textBox1.Text;'什麼/哪裏是'Name'? – 2010-09-23 04:28:51

回答

0

如果你想只是顯示上的按鈕新名稱,你可以更新他們這麼簡單的像所以:

private void name1_Click(object sender, EventArgs e) 
{ 
    firstName.Name = textBox1.Text; 
    button1.Text = "Give $10 to " + firstName.Name; 
} 

也許相同的name2_click(如果你有):

private void name2_Click(object sender, EventArgs e) 
{ 
    secondName.Name = textBox2.Text; 
    button2.Text = "Give $10 to " + secondName.Name; 
} 
1

的鍵位似乎是name1_Click方法,它更新一個firstname對象的名稱到文本框的內容。一旦你完成了,你想刷新按鈕的標題。

我想創建一個新的方法:

public void RefreshButtonCaptions() 
{ 
    button1.Text = "Give $10 to " + firstName.Name; 
    button2.Text = "Give $10 to " + secondName.Name; 
} 

然後從name1_Click調用它:

private void name1_Click(object sender, EventArgs e) 
{ 
    firstName.Name = textBox1.Text; 
    RefreshButtonCaptions() 
} 
相關問題