N.Pelss
N.Pelss

Reputation: 15

Return value from method

I am creating calculator with 20 textboxes - 10 for input, 10 for output. After creating a method into which I put parameter(defined in the first 10 textboxes) I return value to main method.

To get all 10 values is it really necessary to write code for all 10 or more text boxes as I have already started or there is smarter way how to pass into the method textbox parameters and return multiple values at once?

UPDATE:

As you recomended I created List of Tuples and used foreach loop to loop through them, but now i get error: Error 1 Cannot implicitly convert type 'int' to 'string'. Could you help me to point out where the problem is?

private void button1_Click(object sender, EventArgs e)

    {

        List<Tuple<TextBox,TextBox>> tuple1 = new List<Tuple<TextBox,TextBox>>();
        tuple1.Add(Tuple.Create(textBox1, textBox2));
        tuple1.Add(Tuple.Create(textBox3, textBox4));
        tuple1.Add(Tuple.Create(textBox5, textBox6));
        tuple1.Add(Tuple.Create(textBox7, textBox8));


        foreach (Tuple<TextBox,TextBox> box in tuple1)
        {
            var inputBox = box.Item1;
            var outputBox = box.Item2;
            outputBox.Text = MethodA(Convert.ToInt32(inputBox.Text));
        }
    }

    private int MethodA(int Parameter1)
    {
    int A = Parameter1;
    int B = 20;
    int C;

    if (A == 16 && B == 20) { C = 15; } else if (A == 20 && B == 20) { C = 25; } else { C = 0; };
    return C;
    }

Upvotes: 0

Views: 565

Answers (2)

DLeh
DLeh

Reputation: 24405

This might not be the best answer, but it would work:

public class Extensions
{
     public MethodA(this TextBox tb)
     {
         tb.Text = (Convert.ToInt32(tb.Text) + 5).ToString();
     }
}

now you can just call:

 textBox1.MethodA();
 textBox2.MethodA();

...etc.

This isn't necessarily recommended, but it's one way you could simply doing this multiple times.

If you won't be repeating this, it'd probably be better to just inline the logic the same way:

 textBox1.Text = (Convert.ToInt32(textBox1.Text) + 5).ToString();
 textBox2.Text = (Convert.ToInt32(textBox2.Text) + 5).ToString();
 textBox3.Text = (Convert.ToInt32(textBox3.Text) + 5).ToString();

Upvotes: 0

Yogu
Yogu

Reputation: 9455

You could store all the input-output textbox combination in the constructor:

private List<Tuple<TextBox, TextBox>> textBoxes = new List<Tuple<TextBox, TextBox>>();

public Form1() {
    InitializeComponents();
    textBoxes.add(Tuple.Create(textBox1, textBox4);
    // ...
}

And then, in button1_Click, just iterate over all the textboxes:

foreach (Tuple<TextBox, TextBox> boxes in textBoxes) {
    var inputBox = boxes.Item1;
    var outputBox = boxes.Item2;
    outputBox.Text = MethodA(Convert.ToInt32(inputBox.Text));
}

Upvotes: 0

Related Questions