将DataGridView数据保存到SQL Server数据库Winform

时间:2016-04-14 10:32:39

标签: c# sql-server excel winforms datagridview

以下是UI的示例图片:

image

我正在处理一个项目,该项目将导入Excel文件并通过Windows窗体将数据显示到DataGridView。导入Excel文件并在DataGridView中显示它可以正常工作,我遇到的问题是当我点击它显示的“保存”按钮时,将DataGridView中的数据保存为批量插入

错误的屏幕截图:

error

  

未处理的类型' System.ArgumentException'发生在System.Data.dll

当我查看详情时,显示:

  

从对象类型System.Windows.Forms.DataGridViewTextBoxColumn到已知的托管提供程序本机类型不存在映射。

代码:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

using System.Data.OleDb;
using System.Data.SqlClient;

保存按钮代码

     private void btn_Save_Click(object sender, EventArgs e)
        {

            foreach (DataGridViewRow row in dataGridView1.Rows)
            {
                string constring = @"Data Source=databasename;Initial Catalog=Rookies;Integrated Security=True";

                using(SqlConnection con = new SqlConnection(constring))
                {
                    using (SqlCommand cmd = new SqlCommand("INSERT INTO tbl_prospects ([prospectid], [firstname], [lastname], [height], [weight], [age], [college])VALUES(@prospectid, @firstname, @lastname, @height, @weight, @age, @college)", con))
                    {
                        cmd.Parameters.AddWithValue("@prospectid", prospectidDataGridViewTextBoxColumn);
                        cmd.Parameters.AddWithValue("@firstname", firstnameDataGridViewTextBoxColumn);
                        cmd.Parameters.AddWithValue("@lastname", lastnameDataGridViewTextBoxColumn);
                        cmd.Parameters.AddWithValue("@height", heightDataGridViewTextBoxColumn);
                        cmd.Parameters.AddWithValue("@weight", weightDataGridViewTextBoxColumn);
                        cmd.Parameters.AddWithValue("@age", ageDataGridViewTextBoxColumn);
                        cmd.Parameters.AddWithValue("@college", collegeDataGridViewTextBoxColumn);

                        con.Open();
                        cmd.ExecuteNonQuery();
                        con.Close();
                    }
                }
            }
            MessageBox.Show("Successfully Saved!");
        }



    }
}

我还包括以下其他代码

浏览按钮代码

  private void btn_Browse_Click(object sender, EventArgs e)
    {
        OpenFileDialog openFileDialog1 = new OpenFileDialog();

        if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
        {
            this.txt_Path.Text = openFileDialog1.FileName;
        }
    }

加载按钮代码

  private void btn_Load_Click(object sender, EventArgs e)
    {
        string PathConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + txt_Path.Text + ";Extended Properties=\"Excel 8.0;HDR=Yes;\";";
        OleDbConnection conn = new OleDbConnection(PathConn);

        OleDbDataAdapter myDataAdapter = new OleDbDataAdapter("Select * from [" + txt_Sheet.Text + "$]", conn);
        DataTable DT = new DataTable();

        myDataAdapter.Fill(DT);

        dataGridView1.DataSource = DT;
    }

我是编写C#并尝试学习它的新手,这将是我的第一个应用程序,如果有人能提前帮助我做我需要做的事情。

4 个答案:

答案 0 :(得分:2)

您可以直接使用SqlBulkCopy将数据表写入Sql Server,而不是逐行执行。

string constring = @"Data Source=databasename;Initial Catalog=Rookies;Integrated Security=True";

using (var bulkCopy = new SqlBulkCopy(constring ))
{
      bulkCopy.BatchSize = 500;
      bulkCopy.NotifyAfter = 1000;

      bulkCopy.DestinationTableName = "TableName";
      bulkCopy.WriteToServer(dataTable);
 }

还有各种SqlBulkCopy构造函数可以传递SqlConnection和SqlTransaction。

答案 1 :(得分:1)

您可以像这样获取每行的值

foreach (DataGridViewRow row in dataGridView.Rows)
{
    // your code

    cmd.Parameters.AddWithValue("@prospectid",row.Cells["ColumnName"].Value.ToString());
}

答案 2 :(得分:1)

我的第一句话:只使用对象SqlConnextion的1倍,现在最好添加SqlTransaction对象,以避免在DataGridView行出现错误时部分记录数据。 对于答案,您需要指定每列的单元格值

private void btn_Save_Click(object sender, EventArgs e)
{
    string constring = @"Data Source=databasename;Initial Catalog=Rookies;Integrated Security=True";
    SqlConnection con = new SqlConnection(constring);
    SqlTransaction transaction = con.BeginTransaction();
    try
    {
        con.Open();
        foreach (DataGridViewRow row in dataGridView1.Rows)
        {
            using (SqlCommand cmd = new SqlCommand("INSERT INTO tbl_prospects ([prospectid], [firstname], [lastname], [height], [weight], [age], [college])VALUES(@prospectid, @firstname, @lastname, @height, @weight, @age, @college)", con))
            {
                cmd.Parameters.AddWithValue("@prospectid", row.Cells["prospectid"].Value);
                cmd.Parameters.AddWithValue("@firstname", row.Cells["firstname"].Value);
                cmd.Parameters.AddWithValue("@lastname", row.Cells["lastname"].Value);
                cmd.Parameters.AddWithValue("@height", row.Cells["height"].Value);
                cmd.Parameters.AddWithValue("@weight", row.Cells["weight"].Value);
                cmd.Parameters.AddWithValue("@age", row.Cells["age"].Value);
                cmd.Parameters.AddWithValue("@college", row.Cells["college"].Value);
                cmd.Transaction = transaction;
                cmd.ExecuteNonQuery();
            }
        }
        transaction.Commit();
        con.Close();
        MessageBox.Show("Successfully Saved!");
    }
    catch (Exception ex)
    {
        transaction.Rollback();
        con.Close();
        MessageBox.Show(ex.Message);
    }
}

答案 3 :(得分:0)

private void btn_Insert_Click(object sender, EventArgs e)
    {
        if (txtSearsh.Text != "")
        {
            if (dataGridView1.Rows.Count > 0)
            {
                for (int i = 0; i < dataGridView1.Rows.Count ; i++)
                {
                        COI.INSERTdATA(txtSearsh.Text,
                        dataGridView1.CurrentRow.Cells["COIL_NO"].Value.ToString(),
                        dataGridView1.CurrentRow.Cells["SLAB_NO"].Value.ToString(),
                        dataGridView1.CurrentRow.Cells["ORDER_NO"].Value.ToString(),
                        dataGridView1.CurrentRow.Cells["ORDER_NO"].Value.ToString(),
                        dataGridView1.CurrentRow.Cells["ITEM_NO"].Value.ToString(),
                        dataGridView1.CurrentRow.Cells["PROD_TYPE"].Value.ToString(),
                        dataGridView1.CurrentRow.Cells["GRADE"].Value.ToString(),
                        dataGridView1.CurrentRow.Cells["SL_THICK"].Value.ToString(),
                        dataGridView1.CurrentRow.Cells["SL_WIDTH"].Value.ToString(),
                        dataGridView1.CurrentRow.Cells["SL_LENGTH"].Value.ToString(),
                        dataGridView1.CurrentRow.Cells["SL_WGHT"].Value.ToString(),
                        dataGridView1.CurrentRow.Cells["C_THICK"].Value.ToString(),
                        dataGridView1.CurrentRow.Cells["C_WIDTH"].Value.ToString(),
                        dataGridView1.CurrentRow.Cells["C_WT"].Value.ToString(),
                        dataGridView1.CurrentRow.Cells["PRODUCED"].Value.ToString(), "", "", "", "", "", "", DTP.Value, "", "", "", "", "", ""
                        );
                    
                }
                MessageBox.Show("SaccessFouly");
            }
            else { MessageBox.Show("أدخل رقم البرنامج"); }
        }
    }