加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 使用格式化将富文本数据的数据存储到数据库

发布时间:2020-12-15 03:42:57 所属栏目:百科 来源:网络整理
导读:我在wpf中是新的,我想将富文本框的数据及其格式(斜体,彩色,粗体)存储到数据库(Mysql)中. 当我保存数据时,格式化被忽略. 此外,当我从数据库加载到富文本框时,它会显示同一行中的所有文本. 期待您的帮助和建议! public void save() { MySqlConnection conn =
我在wpf中是新的,我想将富文本框的数据及其格式(斜体,彩色,粗体)存储到数据库(Mysql)中.
当我保存数据时,格式化被忽略.
此外,当我从数据库加载到富文本框时,它会显示同一行中的所有文本.
期待您的帮助和建议!
public void save()
    {  

        MySqlConnection conn = new MySqlConnection(connString);
        MySqlCommand command = conn.CreateCommand();      
        string richText = new TextRange(rt1.Document.ContentStart,rt1.Document.ContentEnd).Text;

        string s = WebUtility.HtmlEncode(richText); 
        command.Parameters.AddWithValue("@s",s);           
        command.CommandText = "insert into proc_tra (procedures) values (@s)";
        conn.Open();
        command.ExecuteNonQuery();
        conn.Close();
    }

public void load()

    {   MySqlConnection conn = new MySqlConnection(connString);
        MySqlCommand command = conn.CreateCommand();
        command.CommandText = "select * from proc_tra where id_pt=4";
        rt1.Document.Blocks.Clear();            
        conn.Open();            
        MySqlDataReader dr;
        dr = command.ExecuteReader();
        string k="";           
        while (dr.Read())
        {              
            k += dr["procedures"].ToString();
        }
        var p = new Paragraph();
        var run = new Run();
        run.Text = WebUtility.HtmlDecode(k);
        p.Inlines.Add(run);
        rt1.Document.Blocks.Add(p);
    }

解决方法

要获取将保存在数据库中的格式化文本:
string rtfText; //string to save to db
TextRange tr = new TextRange(richTextBox.Document.ContentStart,richTextBox.Document.ContentEnd);
using (MemoryStream ms = new MemoryStream())
{
    tr.Save(ms,DataFormats.Rtf);
    rtfText = Encoding.ASCII.GetString(ms.ToArray());
}

要还原从数据库检索的格式化文本:

string rtfText= ... //string from db
byte[] byteArray = Encoding.ASCII.GetBytes(rtfText);
using (MemoryStream ms = new MemoryStream(byteArray))
{
    TextRange tr = new TextRange(richTextBox.Document.ContentStart,richTextBox.Document.ContentEnd);
    tr.Load(ms,DataFormats.Rtf);
}

您也可以使用XAML格式,使用DataFormats.XAML加载保存.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读