【问题标题】:Small Bug When When Appending Text To Multiline Text Box (C#)将文本附加到多行文本框时的小错误 (C#)
【发布时间】:2015-09-26 19:07:19
【问题描述】:

我的表单中有包含现有文本的多行文本框,我正在尝试在新行上附加文本行,一切正常,但第一行总是与现有的最后一行一起添加。

例子

文本框保存该值

测试1

我正在使用下面的代码输入新行

txtMasterResults.AppendText(String.Join(Environment.NewLine, "line 2"));

txtMasterResults.AppendText(String.Join(Environment.NewLine, "line 3"));

结果看起来像这样

test1line2

第3行

如何修复文本框的第一行以便从第二行获取新文本?

【问题讨论】:

  • 为什么要使用String.Join 将单个“\n”添加到单个字符串中?
  • \n和simple+有什么问题
  • @GSerg 当我像这样使用 "txtMasterResults.AppendText(String.Concat("\n", autoSuggest));"我也得到了同样的结果
  • @M.kazem Akhgary 请查看以上回复

标签: c# textbox


【解决方案1】:

我会检索旧字符串,删除末尾的所有换行符,然后附加新内容。像这样:

txtMasterResults.Text = txtMasterResults.Text.Trim() + "\n" + newText

【讨论】:

  • 感谢您的回答,但 Environment.Newlines 对我来说似乎更好
  • 你可以用它来代替“\n”,是的
【解决方案2】:

String.Join 使用分隔符连接数组中的字符串。这不是你想要的。

用途:

txtMasterResults.Text += Environment.NewLine + "line 2" + Environment.NewLine + "line 3"; 

请注意
txtMasterResults.Text += "something"; 与
txtMasterResults.Text = txtMasterResults.Text + "something"; 相同

【讨论】:

  • 在添加和删除任何空行之前使用 Environment.New Line 现在可以正常工作:)
猜你喜欢
  • 2013-08-21
  • 1970-01-01
  • 2012-02-17
  • 1970-01-01
  • 1970-01-01
  • 2020-03-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多