【发布时间】:2020-09-21 18:20:18
【问题描述】:
我正在尝试将数据网格中的原始数据一一插入到 SQL 数据库中。
在此代码上循环并仅插入第一行(第一行复制为DataGrid 原始计数)。我需要通过循环一一插入所有行。我该如何解决?
for (int i = 0; i < DGWRelations.Rows.Count; i++)
{
int _PID = Convert.ToInt32(
DGWRelations.CurrentRow.Cells[0].Value.ToString());
int _RELATION = Convert.ToInt32(
DGWRelations.CurrentRow.Cells[1].Value.ToString());
string _NAME = DGWRelations.CurrentRow.Cells[2].Value.ToString();
int _MOBILE = Convert.ToInt32(
DGWRelations.CurrentRow.Cells[3].Value.ToString());
string _NIC = DGWRelations.CurrentRow.Cells[4].Value.ToString();
string _JOB = DGWRelations.CurrentRow.Cells[5].Value.ToString();
string _OTHER = DGWRelations.CurrentRow.Cells[6].Value.ToString();
cmd = new SqlCommand("INSERT INTO [dbo].[DATATBLE] ([PID] ,[Relationship] ,[Name] ,[ContactNo] ,[NIC] ,[Job] ,[OtherDetails]) VALUES (@PID,@Relationship,@Name,@ContactNo,@NIC,@Job,@OtherDetails)", con);
cmd.Parameters.AddWithValue("@PID", _PID);
cmd.Parameters.AddWithValue("@Relationship", _RELATION);
cmd.Parameters.AddWithValue("@Name", _NAME);
cmd.Parameters.AddWithValue("@ContactNo", _MOBILE);
cmd.Parameters.AddWithValue("@NIC", _NIC);
cmd.Parameters.AddWithValue("@Job", _JOB);
cmd.Parameters.AddWithValue("@OtherDetails", _OTHER);
int result = cmd.ExecuteNonQuery();
}
【问题讨论】:
-
几乎可以肯定没有理由从控制中挖掘值并在循环中手动构建 SQL。 DB Provider 对象可以通过一行代码添加、更新和删除任意数量的行更改。有关详细信息,请参阅文档和/或质量教程。
-
相关 - 不要使用addwithvalue
标签: c# sql-server visual-studio loops datagridview