在编写C#时,我是新手,所以请不要对我太苛刻。我以前用ActionScript编码,并注意到它非常相似。
无论如何,我需要基本上构建一个简单的应用程序,其中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;
}
}
}
答案 0 :(得分:1)
关键位似乎是name1_Click
方法,它将firstName对象的Name更新为文本框的内容。完成后,您需要刷新按钮的标题。
我会创建一个新方法:
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()
}
答案 1 :(得分: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;
}