Kevin
Kevin

Reputation: 171

C# Windows Form - How can I call array initialized in click method to other parts of the form

How can I call this array that initializes on a button click event:

private void button1_Click(object sender, EventArgs e)
    {
        int[] n = textBox1.Text.Split(' ').Select(int.Parse).ToArray();

        richTextBox1.Text += "Entered values: ";

        foreach (int num in n)
        {
            richTextBox1.Text += num + " ";
        }

        richTextBox1.Text += "\n";
    }

to other parts of an array, say another click event.

I have tried declaring the array in the form class but that requires the array to have a pre-defined size which is problematic for other parts of the code.

EDIT: Solved! Thanks to the guys at stackoverflow. Solutions and comments were very helpful :D

Upvotes: 1

Views: 61

Answers (3)

Baloo0ch
Baloo0ch

Reputation: 43

Use Generics collection type instead :

        private void button1_Click(object sender, EventArgs e)
    {
        List<int> n= textBox1.Text.Split(' ').Select(int.Parse).ToList();

        richTextBox1.Text += "Entered values: ";

        foreach (int num in n)
        {
            richTextBox1.Text += num + " ";
        }

        richTextBox1.Text += "\n";
    }

You can declare list n in your form class:

List<int> n;

I also recommend use stringBuilder inside your "foreach" to improve performance for longer list. Use following code if you are processing a longer list.

        private void button1_Click(object sender, EventArgs e)
    {
        List<int> n= textBox1.Text.Split(' ').Select(int.Parse).ToList();

        var sBuilder = new StringBuilder();
        sBuilder.Append("Entered values: ");

        foreach (int num in n)
        {
            sBuilder.Append(num + " ");

        }

        sBuilder.AppendLine();
        richTextBox1.Text += sBuilder.ToString();
    }

Upvotes: 0

Lzh
Lzh

Reputation: 3635

You can declare the array in the Form's class without specifying its dimensions simply like this:

int[] n = null; //choose better name, and comment the use of the variable.

The rest of the methods (such as click event handlers) can use it like this:

private void someOtherButton_Click(object sender, EventArgs e)
{
    if(n != null && n.Length > 0)
    {
        //do something with the array
    }
}

Upvotes: 1

MetaColon
MetaColon

Reputation: 2871

You have to make the array to a field (You can initialize the array with the size 0, if that's a problem for your program you have to overthink the rest of your code). It would look like this then:

private int[] n = new int[0];
private void button1_Click(object sender, EventArgs e)
{
    n = textBox1.Text.Split(' ').Select(int.Parse).ToArray();

By the way, I'd strongly suggest not to call the array 'n' but a meaningful name (e.g. _splittedTb1Content).

Upvotes: 0

Related Questions