Jr. Programmer
Jr. Programmer

Reputation: 3

C# parameter passing List<T>

I have this code on C# clearing text textboxes in method way:

public void clearThis(List<TextBox> txtbox){
    foreach (TextBox nTxtbox in txtbox){
        nTxtbox.Text = "";
    }
}

Need help please, how can pass my textboxes on:

clearThis(Arrays.asList(textbox1,textbox2,textbox3)); //something like this method.

this is my sample code:

private void btnCancel_Click(object sender, EventArgs e){
    clearThis();
}

Upvotes: 0

Views: 89

Answers (3)

Sajeetharan
Sajeetharan

Reputation: 222532

If you want to clear TextBoxes on a Form, you could use this method,

void ClearAllText(Control formTest)
{
    foreach (Control c in formTest.Controls)
    {
      if (c is TextBox)
         ((TextBox)c).Clear();
      else
         ClearAllText(c);
    }
}

Upvotes: 0

cdhowie
cdhowie

Reputation: 168988

First, I would change the signature to accept IEnumerable<TextBox> instead of List<TextBox>. The only thing you do is enumerate the argument, so the only capabilities you need are those of an enumerable. This will allow you to pass any sequence of TextBox objects, not just lists.

Second, we have to figure out which text boxes you need. If you already know which you want, then you can simply put them into a TextBox[] (which is an enumerable):

clearThis(new TextBox[] { txtOne, txtTwo, txtThree });

Or, you could pass in some other enumerable, such as:

clearThis(Controls.OfType<TextBox>());

(Note that this will do a shallow search. To perform a deep search, consider using this method that I wrote for another answer. Then you could simply do clearThis(GetControlsOfType<TextBox>(this)).)

Upvotes: 0

MarcinJuraszek
MarcinJuraszek

Reputation: 125620

You can use List<T> constructor and collection initializer syntax:

clearThis(new List<TextBox>() { textbox1, textbox2, textbox3 });

You can also change your method to take TextBox[] array, and mark it using params modifier:

public void clearThis(params TextBox[] txtbox){
    foreach (TextBox nTxtbox in txtbox){
        nTxtbox.Text = "";
    }
}

After that, you'll be able to call it like this:

clearThis(textbox1, textbox2, textbox3);

Upvotes: 2

Related Questions