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.