0

In my program there are multiple players who's stats can all be increased at the same time.

Player 1 is represented by staminaTextBox[0] skillTextBox[0] LuckTexBox[0]

Player 2 is represented by staminaTextBox[1] skillTextBox[1] LuckTexBox[1]

etc.

I need my IncreaseStat method to deal with 3 different type of Textbox Overload e.g. Stamina, Skill, Luck

private void StaminaIncBtn_Click(object sender, EventArgs e)
{
    IncreaseStat(staminaText[0]);
}

private void LuckIncBtn_Click(object sender, EventArgs e)
{
    IncreaseStat(luckText[0]);
}

private void IncreaseStat(TextBox statText)
{
    for (int i = 0; i < 5 ; i++)
    {
        statText[i].Text = "Altered";
    }
}

This method is used to increase all 5 players stats at the same time.

It works fine if they are not control arrays, however I need them to be. I get the error "Cannot apply indexing with [] to an expression of type 'System.Windows.Forms.TextBox". It applies to that fact that inside the method I am saying statText[i].

I do not understand how to get around this problem. Any suggestions would be more than welcome.

Thank you for your time.

8
  • .NET doesn't have control arrays as such (not like VB6 has) - how have you created these? Commented Dec 17, 2012 at 21:17
  • 6
    Your game logic is tied too tightly to the UI. Commented Dec 17, 2012 at 21:18
  • 1
    statText is a single Textbox not an array of Textboxes. Commented Dec 17, 2012 at 21:19
  • You can create control arrays if you just dynmaicaly create them e.g. TextBox[] SkillTextbox = new TextBox[5] Commented Dec 17, 2012 at 21:19
  • 4
    As a rule it's a bad idea to use UI controls to store your data. You should have a Player object which stores the information, and then have functions to either display the information from a Player into the UI, or get a Player object representing what's in the UI (after a user changes something). To update a value from code you should just update the underlying collection of Players. You can use techniques such as Data Binding to help with the transition between objects and UI controls. Commented Dec 17, 2012 at 21:20

1 Answer 1

2

Would this be sufficient (with possible changes by yourself for your need)?

private void IncreaseStat() {
    foreach (TextBox textBox in this.Controls.OfType<TextBox>().Where(x => x.Name.Contains("stamina") || 
            x.Name.Contains("skill") || 
            x.Name.Contains("Luck"))) {
        textBox.Text = "Altered";
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

The logic worked thank you. Needed to alter it a bit like you said. Thanks for your time!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.