将所有记录从DataGridView插入到Sql表C# [英] Insert all record from DataGridView to Sql Table C#

查看:79
本文介绍了将所有记录从DataGridView插入到Sql表C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述




我正在使用C#GUI,我有一个dataGridview和一个按钮,我想从网格中保存所有行和列到sql表请帮帮我.... 。

Hi
I am using C# GUI and i have one dataGridview and one button i want to save all the row and column to sql table from grid please help me.....

推荐答案

are you storing the datagridview row values in a dataset?
if so , you can pass this dataset to a stored procedure to insert into a database table



check这就知道如何将数据集传递给存储过程。

将数据表传递给SQL Server 2008中的存储过程 [ ^ ]


假设你的DataGridView没有绑定到DB(或者它已经包含了你不想再次插入的数据库中的行)你最好使用一个循环:

Assuming your DataGridView is not bound to the DB (or it would already contain rows in the database which you don't want to insert again) you would be best off using a loop:
using (SqlConnection con = new SqlConnection(connectionString))
    {
    using (SqlCommand cmd = new SqlCommand("INSERT INTO MyTable(Column1, Column2) VALUES (@C1, @C2)", con))
        {
        cmd.Parameters.Add(new SqlParameter("@C1", SqlDbType.VarChar));
        cmd.Parameters.Add(new SqlParameter("@C2", SqlDbType.VarChar));
        con.Open();
        foreach (DataGridViewRow row in myDataGridView.Rows)
            {
            if (!row.IsNewRow)
                {
                cmd.Parameters["@C1"].Value = row.Cells[0].Value;
                cmd.Parameters["@C2"].Value = row.Cells[1].Value;
                cmd.ExecuteNonQuery();
                }
            }
        }
    }






为网格数据创建一个xml,并将整个xml发送到存储过程。



在SP内你可以解析它并且可以使用一个插入语句插入记录。



在此如果你有一次打电话给SP。你不需要多次拨打SP。



谢谢:)
Hi,

Create an xml for the grid data and send the entire xml to the store procedure.

Inside the SP you can parse it and can insert records using one insert statement.

In this case you will call SP one time. You don't need to call SP multiple time.

Thanks :)


这篇关于将所有记录从DataGridView插入到Sql表C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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