0

Here is a sample image of the UI:

image

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:

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.

4 Answers 4

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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

3 Comments

this is not the bulk insert , you can find good answer for bulk insert Link - stackoverflow.com/questions/5022531/…
Thanks! I tried this and got this error when I run the file. {"Column named prospectid cannot be found.\r\nParameter name: columnName"}
Check the names of the DataGridView columns in row.Cells["ColumnName"].Value; Normally this is the same column names in the Excel file
1

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

2 Comments

Check the names of the DataGridView columns in row.Cells["ColumnName"].Value
Normally this is the same column names in the Excel file
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("أدخل رقم البرنامج"); }
        }
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.