How to get only NEW text from TextBox?

删除回忆录丶 提交于 2019-12-12 18:21:10

问题


private void tbLog_TextChanged(object sender, TextChangedEventArgs e)
{
    //Get only NEW text added to Log
}

/*
    LOG
    old message...
    old message...
    old message...
    old message...
    NEW message...
    NEW message...
    NEW message...
    NEW message...
    NEW message...
*/  

How to I get only NEW text from the TextBox?


回答1:


Something like this?

private string old_text = "";

private void tbLog_TextChanged(object sender, TextChangedEventArgs e)
{
    if(old_text != tbLog.Text)
    {
        writeLog(tbLog.Text);
        old_text = tbLog.Text;
    }
}



回答2:


Perhaps you should be using the TextChangedEventArgs.Changes property:

var fullText = tbLog.Text;
if (e.Changes.Any())
{
    var additions = e.Changes.Where(tc => tc.AddedLength > 0);
    var newTexts = additions.Select(tc => fullText.Substring(tc.Offset, tc.AddedLength));

    // TODO: Do stuff with the new pieces of text
}



回答3:


For desktop WPF text boxes, you should be able to use TextChangedEventArgs.Changes to enumerate the changes. Note a single event may contain several changes.

The TextChange class has Offset, AddedLength, and RemovedLength properties that give you the exact range of characters that were changed.




回答4:


private void textTx1Asc_TextChanged(object sender, EventArgs e)
{                          
    string s;

    //get only the new chars
    s = textTx1Asc.Text;
    s = s.Remove(0, prev_len);          

    //update prev_len for next time
    prev_len = textTx1Asc.TextLength;

    //s contains only the new characters, process here                
}


来源:https://stackoverflow.com/questions/5438152/how-to-get-only-new-text-from-textbox

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!