这里是UI的样本图像:保存的DataGridView数据到SQL Server数据库的Winform
我工作的一个项目,将导入Excel文件并通过显示数据到一个DataGridView Windows窗体。导入Excel文件并在DataGridView中显示它工作正常,我遇到的问题是将数据保存在DataGridView中作为批量插入,当我单击Save按钮时,它显示一个
错误的屏幕截图:
An unhandled exception of type 'System.ArgumentException' occured in System.Data.dll
当我查看详细信息它显示:
No mapping exists from object type System.Windows.Forms.DataGridViewTextBoxColumn to a known managed provider native type.
代码:
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按钮代码
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!");
}
}
}
我还包括以下
浏览按钮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按钮代码
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#编程新手,想要学习它,如果有人能提前帮助我做我要做的事情,这将是我的第一个应用程序。
这不是批量插入,你可以找到很好的答案批量插入链接 - http://stackoverflow.com/questions/5022531/best-way-to-bulk-insert-from-ac-sharp-datatable/ 5022716#5022716 –
谢谢!我试过这个,当我运行该文件时得到了这个错误。 {“无法找到名为prospectid的列。\ r \ nParameter name:columnName”} – jeff
检查row.Cells [“ColumnName”]中的DataGridView列的名称。通常,这与Excel文件中的列名相同 –