DataGrid查看到SQL Server数据库 [英] DataGrid View To SQL Server Database

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

问题描述

我想从Datagrid View获取数据并在按钮上单击我想将数据保存到sql server数据库表中。

这是一个Windows窗体应用程序。

我将如何从DataGridView动态获取列名并将数据存储到我的表中。请帮帮我。

I want to Get Data from Datagrid View and on button click i want to save the data into sql server database table.
It is an Windows Forms Application.
How i will get the Column Names dynamically from DataGridView and store the data into my table. Please Help me.

推荐答案

这可能有用......但这不是最好的编程习惯



首先创建一个存储过程来获取特定表的所有字段,但是使用默认值null声明它们非常重要,这样如果你不提供它们就不会出现错误...



创建程序spImportUsers



@Name nvarchar(20)= null





然后在你的按钮点击事件中做这样的事情...



This might work...but it's not the best programming practice

first create a storedprocedure that takes all field for your specific table but it's important that you declare them with a default values of null so that if you do not supply them you will not get an error...

create procedure spImportUsers
(
@Name nvarchar(20) = null
)

then in your button click event do something like this...

List<string> lstColumns = new List<string>();
            foreach (DataColumn dc in dataGridView1.Columns)
                lstColumns.Add(dc.ColumnName);
            foreach (DataRow row in dataGridView1.Rows)
            {
                using (SqlConnection conn = new SqlConnection(YourConnectionString))
                {
                    SqlCommand cmd = new SqlCommand("spImportUsers", conn);
                    cmd.CommandType = System.Data.CommandType.StoredProcedure;
                    for (int i = 0; i < lstColumns.Count; i++)
                        cmd.Parameters.AddWithValue(lstColumns[i].ToString(), row[lstColumns[i].ToString()].ToString());
                    conn.Open();
                    cmd.ExecuteNonQuery();
                }
            }





此解决方案将为每一行打开一个连接但是很容易创建一个解决方案,你通过一个值列表发送,我会把它留给你...



另请注意,此解决方案旨在让您知道哪个表是正在导入但不知道将提供哪些列,以及提供的列只是实际在表中的列。



导入多个值时,它总是创建一个事务非常重要,这样当一个事务失败时,所有的值都将被回滚...如果你不知道如何创建一个事务c#side或sql side如果你google它你会得到一些有用的链接



真的希望这可以帮助你...



This solution will open a connection for each row but it will be easy to create a solution where you send through a list of values, I will leave that up to you...

Also take note that this solution is aimed at you knowing which table is being imported but not knowing which columns will be supplied, also that the columns being supplied are only column that are actually in the table.

When importing multiple values it is always important to create a transaction so that when one fails all the values will be rolled back... If you do not know how to create a transaction c# side or sql side if you google it you will get some helpful links

really hopes this helps you...


这篇关于DataGrid查看到SQL Server数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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