简体   繁体   中英

Saving DataGridView data to SQL Server database Winform

Here is a sample image of the UI:

形象

I'm working on a project that will import an Excel file and display the data to a DataGridView via Windows form. 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

Screenshot of the error:

错误

An unhandled exception of type 'System.ArgumentException' occured in System.Data.dll

When I view details it shows :

No mapping exists from object type System.Windows.Forms.DataGridViewTextBoxColumn to a known managed provider native type.

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.

You can directly use SqlBulkCopy to write datatable to Sql Server, rather than doing it row by row.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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