2013-02-28 81 views
2

我在我的C#应用程序中有一个RichtTextBox向用户显示日志。问题是新插入的文本appends低于旧文本,但我想append它在旧文本的顶部。RichTextBox新增文本顶部

例如,当我追加文本 “Newtext” 它看起来像这样:

RichtTextBox

|--------------------- 
|Oldtext    | 
|Newtext    | 
|--------------------- 

但需要看起来像这样:

RichTextBox

|--------------------- 
|Newtext    | 
|Oldtext    | 
|--------------------- 

这是我用来填充我的的代码:

public void DisplayLog(string logtext) 
     { 
      if (logtext != "") 
      { 
       if (this.txtLog.InvokeRequired && !txtLog.IsDisposed) 
       { 
        Invoke(new MethodInvoker(delegate() 
         { 
          txtLog.AppendText(DateTime.UtcNow + ": " + logtext + "\n"); 
         })); 
       } 
       else if (!txtLog.IsDisposed) 
       { 
        txtLog.AppendText(DateTime.UtcNow + ": " + logtext + "\n"); 
       } 
      } 
     } 

有人可以帮我吗?

答:

Inserting at top of richtextbox

+0

检查这篇文章在启动此去:[链接](http://stackoverflow.com/questions/850716/append-text-to-the-beginning-in-the -rich-text-box) [1]:http://stackoverflow.com/questions/850716/append-text-to-the-beginning-in-the-rich-text-box – 2013-02-28 09:48:28

+0

那答案是'不工作。 – Max 2013-02-28 09:51:59

回答

3

使用插入

txtLog.Text = txtLog.Text.Insert(0,DateTime.UtcNow + ": " + logtext + "\n"); 
+0

嗯,使用您的代码后,文本将不会再显示在我的RichTextBox中。 – Max 2013-02-28 09:53:50

+0

已编辑 - 请参阅。 – Derek 2013-02-28 09:58:16

+1

正确它的工作原理,只是发现自己使用此主题回答:http://stackoverflow.com/questions/1818875/inserting-at-top-of-richtextbox – Max 2013-02-28 10:00:59

1

我觉得txtlog是RichTextBox的,你应该在前面加上这一点。

要做到使用

txtlog .SelectionStart = 0; 
txtlog .SelectionLength = 0; 
txtlog .SelectedText = (DateTime.UtcNow + ": " + logtext + "\n"); 
+0

不工作,@Derek的答案工作正常 – Max 2013-02-28 10:00:06