简体   繁体   English

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

[英]Saving DataGridView data to SQL Server database Winform

Here is a sample image of the UI:这是 UI 的示例图像:

形象

I'm working on a project that will import an Excel file and display the data to a DataGridView via Windows form.我正在开发一个项目,该项目将导入 Excel 文件并通过 Windows 窗体将数据显示到 DataGridView。 Importing the Excel file and displaying it in the DataGridView works fine, what I'm having issues is saving the data in the DataGridView as a bulk insert when I click on the Save button it shows an导入 Excel 文件并将其显示在 DataGridView 中工作正常,我遇到的问题是当我单击“保存”按钮时将 DataGridView 中的数据保存为批量插入,它显示一个

Screenshot of the error:错误截图:

错误

An unhandled exception of type 'System.ArgumentException' occured in System.Data.dll System.Data.dll 中发生类型为“System.ArgumentException”的未处理异常

When I view details it shows :当我查看详细信息时,它显示:

No mapping exists from object type System.Windows.Forms.DataGridViewTextBoxColumn to a known managed provider native type.不存在从对象类型 System.Windows.Forms.DataGridViewTextBoxColumn 到已知托管提供程序本机类型的映射。

Code :代码:

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;

SAVE BUTTON CODE保存按钮代码

     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!");
        }



    }
}

I also included the other codes below我还包括下面的其他代码

BROWSE BUTTON CODE浏览按钮代码

  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;
        }
    }

LOAD BUTTON CODE加载按钮代码

  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;
    }

I'm new on coding C# and trying to learn it, this will be my first application if ever, if anyone can help me what I need to do thanks in advance.我是 C# 编码新手并试图学习它,这将是我的第一个应用程序,如果有人可以帮助我,我需要提前感谢。

You can directly use SqlBulkCopy to write datatable to Sql Server, rather than doing it row by row.您可以直接使用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);
 }

There are various SqlBulkCopy constructors to pass SqlConnection and SqlTransaction as well.还有各种 SqlBulkCopy 构造函数来传递 SqlConnection 和 SqlTransaction。

you can get the values from each row like this您可以像这样从每一行获取值

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

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

My first remark: use only 1 times the object SqlConnextion and it is better now to add SqlTransaction object to avoid the partial recording of data in case of error on a line of DataGridView.我的第一句话:只使用1次对象SqlConnextion,现在最好添加SqlTransaction对象,以避免在一行DataGridView出错时部分记录数据。 for the answer you need to specify the value of the cell of each column对于答案,您需要指定每列的单元格的值

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);
    }
}
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("أدخل رقم البرنامج"); }
        }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM