這裏是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文件中的列名相同 –