首页 > 解决方案 > Windows Form c# - 将 RichTextBox 中的每一行插入到 SQL Server 的单独列中

问题描述

我是 .NET Framework 的初学者,所以如果我的代码有一些错误,请指导我。

我正在使用 C# 在 Visual Studio 2014 的 Windows 窗体中创建一个 .NET 应用程序,并将 SQL Server 2014 用于数据库。

我正在尝试实现客户RichTextBox在段落中输入文本的任务也可以有多个段落。每个句子都以句号 (.) 结尾。我想要实现的是输入的文本应该保存到数据库列中,其中每一行都以句号结尾,并且应该保存在不同的列中。

这是我到目前为止在 Visual Studio 中所做的:

private void button1_Click(object sender, EventArgs e)
    {
        string[] values = richTextBox1.Text.Split('$');
        obj.url = "abc.com";
        foreach (string item in values)
        {
            obj.content_result= item;

        }
        dbobj.table_test.Add(obj);
        dbobj.SaveChanges();
        MessageBox.Show("Content Added Successfully");
    }

我的数据库表如下:

表名:Table_test

ID (int - Primary Key - Auto Increment) | Content varchar(MAX) | URL varchar(MAX)

这会将数据保存到以table_test列命名的数据库中;content 和 url 上面的代码应该将数据插入RichTextBox到 content 中,每个句子应该保存在单独的行中。

例如

如果用户在 中输入以下文本RichTextBox

他是个好孩子。他的工作做得很好。他宁愿早点工作,以免造成不便。

上述字符串应保存在数据库中:

ID | Content                                        | URL
--------------------------------------------------------------------
 1 | He is a good boy.                              | abc.com
 2 | He does his work very well                     | abc.com
 3 | He prefer to work early to avoid inconvenience | abc.com

但是,上述数据在数据库中保存为:

ID | Content     | URL
--------------------------------------------------------------------------------------------------------------
 1 | He is a good boy. He does his work very well. He prefer to work early to avoid inconvenience. | abc.com

请帮我解决这个问题,以便每个句子都保存在表格的不同列中。

谢谢 :)

标签: c#sql-serverwindows-forms-designer

解决方案


public class Table
{
    public int Id;
    public string Content;
    public string Url
}

string[] lines = richTextBox1.Text.Split(Environment.NewLine.ToCharArray());
List<Table> items = new List<Table>();
int id = 1;
for (int i=0;i < lines.Length; i++)
{
      string[] tmp = lines[i].Split('|');
      foreach (string x in tmp[1].Split('.'))
          if(!x.Trim()=="")
              items.Add(new Table{ Id = id++ , Content = x + ".", Url = tmp[2] }); 
}

现在您拥有一个数组中的所有项目,可以使用 EF 或只是循环其项目以将它们添加到您的数据库中。


推荐阅读