将 GridView 单元格或数据插入 SQL Server
本文关键字:插入 SQL Server 数据 GridView 单元格 | 更新日期: 2023-09-27 18:33:05
嗨,我正在寻找一种将所有 GridView 单元格或数据插入 SQL Server 表的方法。 我希望这些列与 SQL Server 的列和要添加的每一行相匹配。 行一直在变化。 这可能吗?
这是我尝试过的(没有错误,只是什么都不做)
foreach (GridViewRow GVRow in GridView1.Rows)
{
string PartNumber = string.Empty;
string Qty = string.Empty;
string Price = string.Empty;
string ExtPrice = string.Empty;
PartNumber = GVRow.Cells[1].Text;
Qty = GVRow.Cells[2].Text;
Price = GVRow.Cells[3].Text;
ExtPrice = GVRow.Cells[4].Text;
using (SqlConnection sqlCon5 = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["connectionString"].ConnectionString))
{
SqlCommand scm = new SqlCommand();
scm.Connection = sqlCon5;
scm.CommandText = @"INSERT INTO OrderDetail (OrderNumber, PartNumber, Qty, Price, ExtPrice) VALUES (@OrderNumber, @PartNumber,@Qty,@Price,@ExtPrice)";
scm.Parameters.AddWithValue("@OrderNumber", TextBox1.Text);
scm.Parameters.AddWithValue("@PartNumber", PartNumber.ToString());
scm.Parameters.AddWithValue("@Qty", Qty.ToString());
scm.Parameters.AddWithValue("@Price", Price.ToString());
scm.Parameters.AddWithValue("@ExtPrice", ExtPrice.ToString());
sqlCon5.Open();
scm.ExecuteNonQuery();
sqlCon5.Close();
}
}
尝试改用for loop
。
int rowsCount = GridView1.Rows.Count;
int rowsInserted = 0;
for (int i = 0; i < rowsCount; i++)
{
StrQuery = @"INSERT INTO OrderDetail (OrderNumber, PartNumber, Qty, Price, ExtPrice) VALUES (@OrderNumber, @PartNumber,@Qty,@Price,@ExtPrice)";
scm.CommandText = StrQuery;
scm.Parameters.AddWithValue("@OrderNumber",GridView1.Rows[i].
Cells["columnName"].Value);
scm.Parameters.AddWithValue("@PartNumber",GridView1.Rows[i].
Cells["columnName"].Value);
scm.Parameters.AddWithValue("@Qty",GridView1.Rows[i].
Cells["columnName"].Value);
scm.Parameters.AddWithValue("@Price",GridView1.Rows[i].
Cells["columnName"].Value);
scm.Parameters.AddWithValue("@ExtPrice",GridView1.Rows[i].
Cells["columnName"].Value);
if (scm.ExecuteNonQuery() > 0)
{
rowsInserted++;
}
scm.Parameters.Clear();
}
//check if all rows inserted
if(rowsCount == rowsInserted)
{
//Display successfull message
}
else
{
//Display error message
}
注意* 将columnName
替换为 GridView1
中的实际列名。