Reputation: 59
I am writing a small winform program which has a multiline textbox and a button "Clear". Every string that I append to this textbox, always ends with "\r\n".
textBoxScriptSteps.AppendText(ClickedButton + "\r\n");
I want to erase only the last line on every click of clear button.
Searched in the google but couldn't find any solution. Any help in this please.
Upvotes: 0
Views: 10562
Reputation: 41
I found an simpler way:
TextBox1.Text = TextBox1.Text.Remove(TextBox1.Text.LastIndexOf(Environment.NewLine);
TextBox1.Text = TextBox1.Text.Remove(TextBox1.Text.LastIndexOf(Environment.NewLine);
TextBox1.AppendText("\r\n");
Upvotes: 4
Reputation: 229
I suggest this:
public String RemoveLastLine(String myStr)
{
String result = "";
if (myStr.Length > 2)
{
// Ignore very last new-line character.
String temporary = myStr.Substring(0, myStr.Length - 2);
// Get the position of the last new-line character.
int lastNewLine = temporary.LastIndexOf("\r\n");
// If we have at least two elements separated by a new-line character.
if (lastNewLine != -1)
{
// Cut the string (starting from 0, ending at the last new-line character).
result = myStr.Substring(0, lastNewLine);
}
}
return (result);
}
You can use this function to get your text without the last line.
For example, calling RemoveLastLine();
with "Hello\r\nWorld\r\n"
will give you "Hello\r\n"
.
So you can do textBoxScriptSteps.Text = RemoveLastLine(textBoxScriptSteps.Text);
every time the button is pressed.
The same function more compact:
public String RemoveLastLine(String myStr) {
if (myStr.Length > 2) {
int lastNewLine;
if ((lastNewLine = myStr.Substring(0, myStr.Length - 2).LastIndexOf("\r\n")) != -1)
return (myStr.Substring(0, lastNewLine));
}
return ("");
}
Upvotes: 0
Reputation: 4974
This worked for me
HTML Markup:
<asp:TextBox ID="TextBox1" runat="server" TextMode="MultiLine"></asp:TextBox>
<asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />
Code Behind:
protected void Button1_Click(object sender, EventArgs e)
{
TextBox1.Text = TextBox1.Text.Remove(TextBox1.Text.LastIndexOf(Environment.NewLine));
}
Upvotes: 4
Reputation: 8763
Don't do this.
Keep a List<string>
. Everytime you click add, add the element to the list.
Everytime you click clear remove an element from the end.
Have an UpdateText method that sets the text in the textbox. Call UpdateText at the end of your methods for adding and clearing.
Separate the data from the display.
Upvotes: 1