I have a multiline textbox. Is there any way to add a single character as the first character on every line in the textbox?
Printable View
I have a multiline textbox. Is there any way to add a single character as the first character on every line in the textbox?
Do you mean after the fact or as the text is entered? If it's after the fact then you just get the Lines array and add the character to each element. If it's as the text is entered then you'd have to handle an event and append the character. You may have to experiment a bit but I think KeyUp should do the trick.
Just tested this and it works, although you'll have to add the character to the first line yourself:Code:private void TextBox1_KeyUp(object sender, System.Windows.Forms.KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
this.TextBox1.AppendText("X");
}
}
This is what i mean. Lets say the textbox contains this:
i want to add a character at the begining of every line like:Code:This is line1
this is line 2
this is line3
4
5
6
Sorry for not being so clear in my first post.Code:*This is line1
*this is line 2
*this is line3
*4
*5
*6
Then, like I said in my first post, you get the Lines property and add the character to each element.
I understand what you mean, and thats the way i was going to do it, but i don't understand how (if that makes sense). I have this:Quote:
Originally Posted by jmcilhinney
Code:void BtnAddCharClick(object sender, System.EventArgs e)
{
for (int i = 0; i < tbx.Lines.Length; i++)
{
// Stuck from here :S
}
}
Lines returns an array of String. If you want to add a character to the beginning of a String you would use the '+' concatenation operator. If you want to add a character to the beginning of every element of a String array you would use the concatenation operator in a loop. Once you've made the changes to the array you can then assign it back to the Lines property if you want those changes displayed in the TextBox:Note that Lines is not a live property. By that I mean it is not an existing object that the property returns a reference to. A new array is created each time you get the property. For that reason I have got it only once in the code above. That also means that if you want the changes you make reflected in the TextBox you must assign the changed array back to the property, as I have done in the code above.Code:string[] lines = this.textBox1.Lines;
for (int i = 0; i < lines.Length; i++)
{
lines[i] = "*" + lines[i];
}
this.textBox1.Lines = lines;
Thanks. I thought it would be something similar to that.