我有2种形式:Game和newPlayer。当您在游戏中按一个按钮时,它将打开newPlayer表单的对话框,在此对话框中,有人将键入他/她的名字,并在comboBox中选择红色,绿色,蓝色或黄色之间的颜色。我将该信息保存在2个变量中:名称(字符串)和颜色(int-comboBox的索引)。我想将这两个变量传递给Game表格。
我尝试将它们统一为一个字符串,并且仅将一个变量传递给Game形式,但是没有成功。
public partial class Game : Form
{
static int nPlayers = 4;
static List<Player> players = new List<Player>();
public string name = "";
private void button3_Click(object sender, EventArgs e)
{
using (newPlayer np = new newPlayer())
{
if (np.ShowDialog() == DialogResult.OK)
{
this.name = np.TheValue;
}
}
MessageBox.Show("Welcome " + name + "!");
}
然后:
public partial class newPlayer : Form
{
public string name = "";
public string TheValue
{
get { return this.name; }
}
private void button1_Click(object sender, EventArgs e)
{
if (textBox1.Text != "")
{
if (comboBox1.SelectedIndex > -1)
{
this.name = textBox1.Text + comboBox1.SelectedIndex.ToString();
MessageBox.Show(newPlayer.name);
this.Close();
} else
{
MessageBox.Show("Write your name and choose a color!");
}
} else
{
MessageBox.Show("Write your name and choose a color!");
}
}
例如,在newPlayer的MessageBox上,它正确显示为“ Name1”。但是在游戏的消息框上,它显示为空。有人可以帮忙吗?
答案 0 :(得分:0)
关闭表单时,您忘记设置DialogResult
。
尝试一下:
this.DialogResult = DialogResult.OK;
this.Close();
如果我正在编写此代码,则可能会更像这样:
游戏:
public partial class Game : Form
{
public Game()
{
InitializeComponent();
}
private string _playerName = "";
private void button3_Click(object sender, EventArgs e)
{
using (NewPlayer np = new NewPlayer())
{
if (np.ShowDialog() == DialogResult.OK)
{
_playerName = np.PlayerName;
MessageBox.Show($"Welcome {_playerName}!");
}
}
}
}
NewPlayer:
public partial class NewPlayer : Form
{
public NewPlayer()
{
InitializeComponent();
}
private string _playerName = "";
public string PlayerName
{
get { return _playerName; }
}
private void button1_Click(object sender, EventArgs e)
{
if (textBox1.Text != "" && comboBox1.SelectedIndex > -1)
{
_playerName = $"{textBox1.Text}{comboBox1.SelectedIndex}";
MessageBox.Show(_playerName);
this.DialogResult = DialogResult.OK;
this.Close();
}
else
{
MessageBox.Show("Write your name and choose a color!");
}
}
}