[英]Saving DataGridView data to SQL Server database Winform
这是 UI 的示例图像:
我正在开发一个项目,该项目将导入 Excel 文件并通过 Windows 窗体将数据显示到 DataGridView。 导入 Excel 文件并将其显示在 DataGridView 中工作正常,我遇到的问题是当我单击“保存”按钮时将 DataGridView 中的数据保存为批量插入,它显示一个
错误截图:
System.Data.dll 中发生类型为“System.ArgumentException”的未处理异常
当我查看详细信息时,它显示:
不存在从对象类型 System.Windows.Forms.DataGridViewTextBoxColumn 到已知托管提供程序本机类型的映射。
代码:
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;
保存按钮代码
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!");
}
}
}
我还包括下面的其他代码
浏览按钮代码
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;
}
}
加载按钮代码
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# 编码新手并试图学习它,这将是我的第一个应用程序,如果有人可以帮助我,我需要提前感谢。
您可以直接使用SqlBulkCopy 将数据表写入Sql Server,而不是逐行进行。
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);
}
还有各种 SqlBulkCopy 构造函数来传递 SqlConnection 和 SqlTransaction。
您可以像这样从每一行获取值
foreach (DataGridViewRow row in dataGridView.Rows)
{
// your code
cmd.Parameters.AddWithValue("@prospectid",row.Cells["ColumnName"].Value.ToString());
}
我的第一句话:只使用1次对象SqlConnextion,现在最好添加SqlTransaction对象,以避免在一行DataGridView出错时部分记录数据。 对于答案,您需要指定每列的单元格的值
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("أدخل رقم البرنامج"); }
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.