简体   繁体   中英

How to pass an array of textBox to another form in c#

I'am a 2 months c# studient.

I have 3 textBox array defined in a form and I want pass to program.cs

Those names below are declared as public and it works in the form where they are declared but as I call same thing from other forms, I want to put it in program.cs under the public GeneralMethodes

        _textBox = new TextBox[] { textBox1, textBox2, textBox3, textBox4, textBox5, textBox6, textBox7, textBox8, textBox9 };
        _textBox1 = new TextBox[] { textBox10, textBox11, textBox12, textBox13, textBox14, textBox15, textBox16, textBox17, textBox18 };
        _textBox2 = new TextBox[] { dateTxt, deadLineTxt, qtyprodTxt };

In program.cs I have the code below:

public static void EraseTextBox(Form[] MyBox, Form[] MyBox1)

    {
        for (int i = 0; i < 9; ++i)
        {
            MyBox[i].Text = "";
            MyBox1[i].Text = "";
        }

In my caller form I have this code:

GeneralMethodes.EraseTextBox(_textBox, _textBox1); // This works if the code is in the same form.

I tried with Type[], string[],Array[],Object[],object[] but they don't work and don't accept .Text except Form.

What should I put for defining this array in EraseTextBox(? MyBox, ? MyBox1) ?

public static void EraseTextBox(TextBox[] MyBox, TextBox[] MyBox1)

{
    for (int i = 0; i < 9; ++i)
    {
        MyBox[i].Text = "";
        MyBox1[i].Text = "";
    }

Probably your error is that you're using Form[] instead of TextBox[] on EraseTextBox

As others have said, EraseTextBox should accept a TextBox[] .

Besides just modifying the type of the array parameter, in EraseTextBox you should really be going off of the length of the array instead of a hardcoded upper limit. The EraseTextBox function should be using the length of the array to determine when to stop iterating. With a hard coded upper limit, you can use the code and either not clear all the text boxes, or get an IndexOutOfRangeException .

You should also consider not accepting two arrays. What happens when the length of one array does not match the other, one or the other will not be entirely cleared, or an exception could occur.

public static void EraseTextBoxes(TextBox[] boxes)
{ 
    for (var i = 0; i < boxes.Length; ++i)
        boxes[i].Text = "";
}

Then you call it like so:

EraseTextBoxes(_textBox);
EraseTextBoxes(_textBox1);

An array is a collection of objects with a certain type. You said you want an array of text boxes, so you want to declare an array that can hold many TextBox es.

For example,

TextBox[] _textBoxes = new TextBox[3];

would create an array that can hold 4 TextBox es.

In your case, change Form[] MyBox to TextBox[] MyBox .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM