0

I have a window form application, inside this application, there have several textbox and want to replace the breakline and send out as email in one click. Since i have multiple textbox, instead of writing like this:

 string text = textBox1.Text;
 text = text.Replace("\n", "<br/>");
 string text2 = textBox2.Text;
 text2 = text2.Replace("\n", "<br/>");
 ...

        string textBody ="<tr bgcolor = '#C39BD3'><td>Name</td><td>" + text + "</td></tr>" +"<tr bgcolor = '#C39BD3'><td>Age</td><td>" + text2 + "</td></tr>" + ...

is there any ways to replace the line in these textbox in one time?

I try to put in a loop:

        for (int i = 1; i < 20; i++)
        {TextBox txtbox = (TextBox)this.Controls.Find("textBox" + i, true)[0]; }

I stuck at here. Any suggestion?

yancy
  • 17
  • 6

1 Answers1

2

Your Form is a Control, which has a property Controls This property "Gets the collection of controls contained within the control".

You can use Enumerable.OfType to filter this so you get only the TextBoxes.

Is there any ways to replace the line in these textbox in one time?

You'll need a foreach to replace the text:

var textBoxesToUpdate = this.Controls.OfType<TextBox>();
foreach (TextBox textBox in textBoxesToUpdate)
{
    string proposedText = textBox.Text.Replace("\n", "<br/>");
    textBox.Text = proposedText;
} 

I also see this in your question

string textBody = "<tr bgcolor = '#C39BD3'><td>Name</td><td>" + text1 + "</td></tr>"
                + "<tr bgcolor = '#C39BD3'><td>Age</td><td>"  + text2 + "</td></tr>"
                + ...

I don't know what you want with this. Consider to edit the question and change this.

Harald Coppoolse
  • 28,834
  • 7
  • 67
  • 116
  • Hi Harald, Thanks for the help and suggestion. For the 'string textBody' part, because i want to send it out as email, so that part is a html table for email. The 'text1' is the textbox that let user to key in the message. – yancy Nov 04 '20 at 01:06
  • When i send it out, it read my message at one line..so i have to use the 'replace' function to break the line. But because i have many textbox, i thinking of not to replace the textbox one by one. – yancy Nov 04 '20 at 01:21