2010-01-11 61 views
0

我有一個小的Windows客戶端應用程序數據綁定到單個表後端。 我使用VS 2005中的嚮導創建了一個DataSet,並自動創建底層適配器和一個GridView。我也有一個RichText控件並將其綁定到此DataSet。目前爲止,但在RichTextbox中顯示數據之前,我需要隨時替換某些字符(〜)。這可以做到嗎?富文本框。 .NET 2.0內容格式化

回答

0

您需要處理綁定的FormatParse事件。

Binding richTextBoxBinding = richTextBox.DataBindings.Add("Text", bindingSource, "TheTextColumnFromTheDatabase"); 
richTextBoxBinding.Format += richTextBoxBinding_Format; 
richTextBoxBinding.Parse += richTextBoxBinding_Parse; 

Format事件,內部值轉換爲格式化表示:

private void richTextBoxBinding_Format(object sender, ConvertEventArgs e) 
{ 
    if (e.DesiredType != typeof(string)) 
     return; // this conversion only makes sense for strings 

    if (e.Value != null) 
     e.Value = e.Value.ToString().Replace("~", "whatever"); 
} 

Parse情況下,格式化表示轉換到內部值:

private void richTextBoxBinding_Parse(object sender, ConvertEventArgs e) 
{ 
    if (e.DesiredType != typeof(string)) 
     return; // this conversion only makes sense for strings (or maybe not, depending on your needs...) 

    if (e.Value != null) 
     e.Value = e.Value.ToString().Replace("whatever", "~"); 
} 

注你只需要處理Parse事件,如果你的綁定是雙向的(即用戶可以修改文本和chan ges被保存到數據庫)

+0

Thomas,謝謝你的回答。我正在做同樣的事情,並且意外地在「richTextBox1_TextChanged」上發現了這個事件,並且在這個事件中,我添加了這行代碼「richTextBox1.Text = richTextBox1.Text.Replace(」〜「,」\ n「);」。並且還使控件只讀,以便用戶不能更改其中的文本並觸發TextEvent_Changes事件。 你認爲這種方法好嗎/好/壞? 再次感謝您的輸入。 Ranjit – Ranjit 2010-01-12 15:51:54

+0

您不應該顯式更改Text屬性,因爲它會通過綁定更新數據源...格式和分析事件的設計正是爲了您想要做的 – 2010-01-12 16:55:59