2010-01-11 60 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