Reputation: 1916
I am copying data from excel and pasting it to the windows form with button click.
The copied data from excel is being split and populate the four textboxes. All the texboxes are populated as expected but the last textbox get extra "\r\n". It doesn't show up in the textbox but if i put break point and look at the variable there is extra \r\n.
The variable I am grabbing looks like this test\r\n.
I know I can replace this with "" but is there a way to avoid this happening.
Here is the code for my paste event handler.
if (Clipboard.GetText() != null)
{
string s = Clipboard.GetText();
string[] lines = s.Split('\t');
if (lines.Length < 3)
{
DialogResult result = MsgBox.Show("Please copy valid data with tab space.", "Incorrect data format.", MsgBox.Buttons.OK, MsgBox.Icon.Exclamation, MsgBox.AnimateStyle.ZoomIn);
//MessageBox.Show("Please copy valid data with tab space.", "Incorrect data format.", MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1);
}
else
{
green_textBox_ref.Text = lines[0].Replace(" ", "");
green_textBox1.Text = lines[1].Replace(" ", "");
green_textBox2.Text = lines[2].Replace(" ", "");
green_textBox3.Text = lines[3].Replace(" ", "");
green_textBox_ref.Enabled = false;
green_textBox1.Enabled = false;
green_textBox2.Enabled = false;
green_textBox3.Enabled = false;
paste_green.Enabled = false;
}
}
else
{
DialogResult result = MsgBox.Show("There is no data to paste.", "No data", MsgBox.Buttons.OK, MsgBox.Icon.Error, MsgBox.AnimateStyle.ZoomIn);
//MessageBox.Show("There is no data to paste.", "No data", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1);
}
}
And here is the screen shot of break point.
Upvotes: 0
Views: 1279
Reputation: 13971
New line within an Excel cell is the CR character, which is "\r" in C#.
As answered by GSerghttp.
You could remove the extra content by :
s.ToString().TrimEnd( '\r', '\n' );
or replace as :
text = text.Replace("\r\n", "");
Example:
string OriginString = "\r\n\r\nText goes here\r\n";
string NewString = OriginString.Replace("\r\n", "");
Upvotes: 0
Reputation: 2072
As you can't avoid \t, you can't avoid getting \r\n. This is how the pasting client knows about tabular data using \t \r and \n.
If you copy a Excel range which has more than one Rows, you will get many \r\n.
Best is to remove \r\n using String.Replace
method.
Upvotes: 0
Reputation: 66439
You could remove that ending line newline a few different ways. Since you're already splitting the string, you could tell it to treat the newline as an additional delimiter, and remove empty substrings.
string[] lines =
s.Split(new[] {"\t", Environment.NewLine}, StringSplitOptions.RemoveEmptyEntries);
Alternatively, you could use TrimEnd()
to trim specific characters off the end of a string.
green_textBox3.Text = lines[3].Replace(" ", "").TrimEnd('\r', '\n');
I doubt there's a way to prevent it from being included on the ClipBoard when you copy from Excel.
Upvotes: 1