将datagridview中的所有数据保存到SQL表中 [英] Saving all the data in datagridview into SQL table

查看:80
本文介绍了将datagridview中的所有数据保存到SQL表中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,

有人可以帮我这个吗,
我想将datagridview中的数据保存到SQL数据库表中

任何帮助都将得到应用!

谢谢

解决方案

使用以下属性读取datagridview的每一行元素

String readRow = DataGridView.Rows[i];



可以使用以下代码检索列数

for (int i=0; i<datagridview.columncount)>
  myDataColumns[i] = DataGridView.Column[i];



我们可以使用ADO .NET Entity框架将读取的数据保存到SQL表中.为此,我们需要使用自定义方法(如
)将数据元素转换为实体

 private EntityRecord ConvertEntityToData(myDataRecord data)
{
     if (data == null)
     {
         return null;
     }
     else
     {
         return (new EntityRecord
         {
             EmployeeID = data.EmpID,
             EmployeeName = data.EmpName
         });
     }
 }



最后,将Entity DBContext的SaveChanges()方法调用为

myDbEntities mydb=new myDbEntities();
......
mydb.myTable.Add(ConvertEntityToData(dataRecord);
mydb.SaveChange();


您可以具有一个更新按钮,单击此按钮可以编写代码以将更改保存在数据库中.

您可以尝试使用此方法来构建更新查询:

 SqlCommandBuilder构建=  SqlCommandBuilder(adapter); 



然后在更新按钮上单击事件,写以下行:

 adapter.Update(dt); 



在这里,适配器是SqlDataAdapter的对象,而dt是DataTable的对象.并确保您的表包含主键.

请参阅此以了解更多信息:
http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommandbuilder.aspx?ppud = 4 [ 解决方案

Read each row elements of datagridview using the below property

String readRow = DataGridView.Rows[i];



Number of columns can be retrieved using the below code

for (int i=0; i<datagridview.columncount)>
  myDataColumns[i] = DataGridView.Column[i];



We can save the read data into SQL table using ADO .NET Entity framework. For that, we need to convert the data elements into entity using custom method like

 private EntityRecord ConvertEntityToData(myDataRecord data)
{
     if (data == null)
     {
         return null;
     }
     else
     {
         return (new EntityRecord
         {
             EmployeeID = data.EmpID,
             EmployeeName = data.EmpName
         });
     }
 }



finally, call SaveChanges() method of Entity DBContext as

myDbEntities mydb=new myDbEntities();
......
mydb.myTable.Add(ConvertEntityToData(dataRecord);
mydb.SaveChange();


You can have a update button and on clicking on this you can code to save the changes in database.

You can try this for building the update query:

SqlCommandBuilder build = new SqlCommandBuilder(adapter);



and on update button click event write the below line:

adapter.Update(dt);



here adapter is an object of SqlDataAdapter and dt is object of DataTable. And make sure your table contains Primary key.

refer this to learn more:
http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommandbuilder.aspx?ppud=4[^]

hope it helps :)

for further queries comment here!!


这篇关于将datagridview中的所有数据保存到SQL表中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆