2017-05-06 61 views
0

我想在Visual Studio中創建一個Windows窗體應用程序。我想要做的是,當用戶在RichTextBox中鍵入內容時,它會刪除您鍵入的內容並用預設的字母替換它。我到目前爲止是:如何用預設文本替換輸入的文本c#

private void richTextBox1_TextChanged(object sender, EventArgs e) 
{ 
    string text = richTextBox1.Text; 
    richTextBox1.Text = text.Remove(text.Length - 1, 1); 
} 

因此,當你鍵入一個字母它會刪除它。之後我想要的是它添加了預設文本的一個字母。所以我們假設你有文字This is a test text that is reasonably long。當用戶輸入「A」時,會出現字母「T」。當用戶輸入另一個字母時,會出現下一個字母'h',等等,直到顯示全文This is a test text that is reasonably long,然後您不能再輸入。

這裏是更多的代碼,如果需要的話:

private void button6_Click(object sender, EventArgs e) 
{ 
    webBrowser1.Navigate(textBox1.Text); 
} 

private void button5_Click(object sender, EventArgs e) 
{ 
    webBrowser1.Navigate("www.google.com"); 
} 

private void richTextBox1_TextChanged(object sender, EventArgs e) 
{ 
    string text = richTextBox1.Text; 
    richTextBox1.Text = text.Remove(text.Length - 1, 1); 
} 
+0

richTextBox1.Text = text.Substring(0,richTextBox1.Length); ? – VirCom

回答

0

你可以做一些類似的。

public string longText = "This is a test text that is reasonably long"; 
private void RichTextBox1_TextChanged(object sender, EventArgs e) 
{    
    // I don't know if the user can press enter 
    // and give you an empty string so this checks that 
    // and that richTextBox1.Text is not greater than the 
    // text you want replace with, in this case longText 
    if (richTextBox1.Text.Length <= longText.Length && richTextBox1.Text.Length > 0) 
    { 
     string text = richTextBox1.Text; 
     // removes the last character, Remove returns 
     // a new string so you have to save it somewhere 
     text = richTextBox1.Text.Remove(text.Length - 1, 1); 
     // here you add the character you want to replace 
     text += longText[richTextBox1.Text.Length - 1]; 
     richTextBox1.Text = text; 
    } 
    else if (richTextBox1.Text.Length > longText.Length) 
    { 
     // this case is when the user wants to add another 
     // character but the whole text it's been already replaced 
     richTextBox1.Text = richTextBox1.Text.Remove(richTextBox1.Text.Length - 1, 1); 
     } 
    } 

讓我知道這是否對您有幫助。

+0

歡迎來到SO。請閱讀此[如何回答](http://stackoverflow.com/help/how-to-answer)以提供高質量的答案。 – thewaywewere

+0

我似乎在if(enrichedText.Length <= longText.Length)這一行發生了一個錯誤,並說「System.NullReferenceException:'對象引用沒有設置爲對象的實例。'」和「enrichedText was空值」。你的答案中有沒有我想念的東西? – MainframeHacker

+0

對不起@MainframeHacker,我做了一些與我的VS,我無法測試。我已經編輯了答案並給出了更好的答案,我想嘿嘿。問候! – santipl

相關問題