c# - 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
请帮我解决这个问题,以便每个句子都保存在表格的不同列中。
谢谢 :)
解决方案
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 或只是循环其项目以将它们添加到您的数据库中。
推荐阅读
- reactjs - React setState 不适用于侦听器模式
- sql - QSqlTableModel 和 QSQLITE 没有显示正确的列和标题
- python - 从 CNN 层获取过滤器值
- react-native - npm install Expo cli,停在extraxt:rxjs
- angular - Angular 7 从选择器解析组件工厂
- autodesk-forge - Fusion 360 文件列表的 AutoDesk API
- r - 如何在 R 中回收字符向量?
- firebase - 使用 Firebase.Core 框架的两个 Cordova 插件在构建应用程序时导致冲突
- java - 在 Java / mysql 中批量插入的更好方法?插入表值(...),(...)?或preparedStatement.addBatch()
- python - 如何计算每个项目的平均索引位置