Adding new line to a label dynamically in c
In C#, you can add a new line to a Label
control dynamically by using the Text
property and concatenating the new line with the existing text. Here are a few ways to do it:
Method 1: Using +=
operator
Label myLabel = new Label();
myLabel.Text = myLabel.Text + "\r\nNew line added!";
This will add a new line to the end of the existing text.
Method 2: Using StringBuilder
Label myLabel = new Label();
StringBuilder sb = new StringBuilder(myLabel.Text);
sb.AppendLine("New line added!");
myLabel.Text = sb.ToString();
This method is more efficient if you need to add multiple lines of text.
Method 3: Using Environment.NewLine
Label myLabel = new Label();
myLabel.Text = myLabel.Text + Environment.NewLine + "New line added!";
This method uses the Environment.NewLine
property to get the correct newline character for the current platform (e.g., \r\n
on Windows, \n
on macOS/Linux).
Remember to update the Label
control's Text
property after modifying the text to reflect the changes.
You can also use this approach to add multiple lines of text to a Label
control dynamically:
Label myLabel = new Label();
myLabel.Text = "Line 1\r\nLine 2\r\nLine 3";