我在gridview中获得了excel值,现在我需要将所有行的值插入到sql server 2008中。
当我尝试迭代Gridview行时,它会在dg_AgentSFR.Rows附近的for循环中抛出错误,因为“DataGrid'不包含'Rows'的定义”
这是我的代码:
protected void savedatafromgv()
{
foreach (GridViewRow g1 in ***dg_AgentSFR.Rows)***
{
SqlConnection con = new SqlConnection(strConnString);
SqlCommand cmd = con.CreateCommand();
cmd = new SqlCommand("INSERT INTO TB_TransAgenSeaFreightRate(POL,POD,FORWARDER,FORWARDER REFERENCE,SHIPPING LINE,CONTAINER TYPE,CONTAINER SIZE,VALIDITY FROM,VALIDITY TO,BASIC RATE,PAF,CAF,PSS,TOTAL AMOUNT,REE DAYS,CREDIT DAYS,NIT DEPOSIT,COMPANYID,ISACTIVE) values ('" + g1.Cells[0].Text + "','" + g1.Cells[1].Text + "','" + g1.Cells[2].Text + "','" + g1.Cells[3].Text + "','" + g1.Cells[4].Text + "','" + g1.Cells[5].Text + "','" + g1.Cells[6].Text + "','" + g1.Cells[7].Text + "','" + g1.Cells[8].Text + "','" + g1.Cells[9].Text + "','" + g1.Cells[10].Text + "','" + g1.Cells[11].Text + "','" + g1.Cells[12].Text + "','" + g1.Cells[13].Text + "','" + g1.Cells[14].Text + "','" + g1.Cells[15].Text + "','" + g1.Cells[16].Text + "',1,'" + TXTCompanyID.Text + "')", con);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
Response.Write ("Records inserted successfully");
}
请帮我解决这个问题。
提前致谢。
答案 0 :(得分:1)
Datagrid
不包含rows
的定义。它不是rows
,而是items
。
使用此
foreach (DataGridItem Dr in dg_AgentSFR.items)
并使用参数化查询来避免How does SQLParameter prevent SQL Injection
cmd = new SqlCommand("INSERT INTO TB_TransAgenSeaFreightRate(POL,POD,FORWARDER....) values (@POL,@POD,@FORWARDER)
答案 1 :(得分:0)
试试这段代码
if(dg_AgentSFR.Rows.Count>0)
{
foreach (GridViewRow g1 in dg_AgentSFR.Rows)
{
SqlConnection con = new SqlConnection(strConnString);
SqlCommand cmd = con.CreateCommand();
cmd = new SqlCommand("INSERT INTO TB_TransAgenSeaFreightRate(POL,POD,FORWARDER,FORWARDER REFERENCE,SHIPPING LINE,CONTAINER TYPE,CONTAINER SIZE,VALIDITY FROM,VALIDITY TO,BASIC RATE,PAF,CAF,PSS,TOTAL AMOUNT,REE DAYS,CREDIT DAYS,NIT DEPOSIT,COMPANYID,ISACTIVE) values ('" + g1.Cells[0].Text + "','" + g1.Cells[1].Text + "','" + g1.Cells[2].Text + "','" + g1.Cells[3].Text + "','" + g1.Cells[4].Text + "','" + g1.Cells[5].Text + "','" + g1.Cells[6].Text + "','" + g1.Cells[7].Text + "','" + g1.Cells[8].Text + "','" + g1.Cells[9].Text + "','" + g1.Cells[10].Text + "','" + g1.Cells[11].Text + "','" + g1.Cells[12].Text + "','" + g1.Cells[13].Text + "','" + g1.Cells[14].Text + "','" + g1.Cells[15].Text + "','" + g1.Cells[16].Text + "',1,'" + TXTCompanyID.Text + "')", con);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
Response.Write ("Records inserted successfully");
}
答案 2 :(得分:0)
ASP.NET中的数据网格确实不包含属性Rows
。另一方面,GridView确实包含属性Rows
。更多信息:
我建议您使用GridView
,这是DataGrid的继承者。另一个重要提示:使用SQL参数而不仅仅是字符串查询(SQL注入)。
答案 3 :(得分:0)
确保使用 GridViewRowEventArgs 而非GridViewCommandEventArgs
protected void gvSample_RowDataBound(object sender,GridViewRowEventArgs e)
{
//您的代码
}