今天有个需求,将Data Grid View的数据导入到数据库中
操作思路
将Data Grid View按照每行分开,然后获取每行的每个单元格,使用SQL语句存到数据库中。既然思路清晰了,那么我们再来研究一下如果将Data Grid View每行都分开,Data Grid View自带一个获取每行值的叫做DataGridViewRow,下面就是使用DataGridViewRow 的演示代码。
DataGridViewRow row in dataGridView1.Rows
算了,直接上例子吧,太简单,没啥写的
if (dataGridView1 != null)
{
int Num = 0;
foreach (DataGridViewRow row in dataGridView1.Rows)
{
Num++;//计算数据数
//获取每行的每个单元格值
string PlanID = row.Cells[1].Value?.ToString();
string DeviceID = row.Cells[2].Value?.ToString();
string MaterialID = row.Cells[3].Value?.ToString();
string ProductID = row.Cells[4].Value?.ToString();
string MaterialCode = row.Cells[5].Value?.ToString();
string ProductIDSmall = row.Cells[6].Value?.ToString();
//判断获取的值是否为空,为导入做准备,如果为空不记录
if (string.IsNullOrEmpty(PlanID) || string.IsNullOrEmpty(DeviceID) || string.IsNullOrEmpty(MaterialCode) || string.IsNullOrEmpty(ProductID) || string.IsNullOrEmpty(MaterialID) || string.IsNullOrEmpty(ProductIDSmall))
{
continue;
}
// MessageBox.Show(PlanID + productCode + productID + DeviceID + productIDSmall + MaterialID);
//存入数据库,
string Str = "insert into tb_Materialcode(PlanID,DiviceID,ProductID,MaterialID,Materialcode,ST,Count,FramecCode,Size,ProductIDSmall)values('{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}','{9}')";
Str = string.Format(Str, PlanID, DeviceID, ProductID, MaterialID, MaterialCode, 0, 0, null, 0, ProductIDSmall);
if (SQLHelper.ExecuteNoQuery(Str) > 0)
{
MessageBox.Show("第" + Num + "条数据成功录入");
}
}
}
//ExecuteNoQuery代码
public static int ExecuteNoQuery(string cmdText)
{
using (SqlConnection sqlConn = new SqlConnection(connString))
{
sqlConn.Open();
SqlCommand sqlCommand = new SqlCommand(cmdText, sqlConn);
int rows = sqlCommand.ExecuteNonQuery();
if (rows <= 0)
{
LogHelper.Monitor(cmdText + "\r\n" + "操作数据库失败!");
}
return rows;
}
}