Reputation: 2576
I have a game I'm making in .NET at the moment. Right now I have something like this for determining which textbox belongs to which player:
switch(player.ID) {
case 1: storeRandPlayerInfo = textbox1.Text;
break;
case 2: storeRandPlayerInfo = textbox2.Text;
break;
case 3: storeRandPlayerInfo = textbox3.Text;
break;
}
My question is, is there a way to do something like Windows.Textbox["textbox"+player.ID].Text; Know what i mean? I can't find anything online so I assume it's not possible but I just wanted to know.
Upvotes: 0
Views: 203
Reputation: 13178
Personally I would use a dictionary; you are describing a mapping, and that's what dictionaries do best. You can do it either with your ID, or the objects themselves:
// using ID as the key
private readonly Dictionary<int, TextBox> mPlayerTextBoxes;
// ...or using object as the key
private readonly Dictionary<Player, TextBox> mPlayerTextBoxes;
// in form constructor, after InitializeComponent call:
// using ID as the key
mPlayerTextBoxes = new Dictionary<int, TextBox>
{
{ player1.ID, textbox1 },
{ player2.ID, textbox2 },
{ player3.ID, textbox3 }
};
// using object as the key
mPlayerTextBoxes = new Dictionary<Player, TextBox>
{
{ player1, textbox1 },
{ player2, textbox2 },
{ player3, textbox3 }
};
// then when you want a textbox, given a player:
// using ID
TextBox textBox = mPlayerTextBoxes[player.ID];
// using object
TextBox textBox = mPlayerTextBoxes[player];
Upvotes: 0
Reputation: 5609
You can just use the indexing of "this.Controls" (point to note, "this.Controls" will only contain the top level controls on the form, controls within a groupBox for instance will be in a collection in "this.groupBox1.Controls", so index into that collection rather than "this.Controls")
private TextBox getPlayersBox(int player)
{
string expected = "textBox" + player.ToString();
if (this.Controls.ContainsKey(expected))
return this.Controls[expected] as TextBox;
else
return null;
}
Upvotes: 0
Reputation: 35235
Surely there is a way. One of them is:
// define and init
TextBox[] playerBoxes = new TextBox[] { textBox1, textBox2, textBox3 };
// use
storeRandPlayerInfo = playerBoxes[player.ID - 1];
Upvotes: 4
Reputation: 39268
You can do something like this
private TextBox GetPlayerTextBox(int playerId)
{
string textBoxName = string.Format("TextBox{0}", playerId);
return this.Controls.OfType<TextBox>().Where(t => t.Name == textBoxName).Single();
}
Upvotes: 0