我试图遍历所有ASP.Net gridview行并将它们插入到数据库中。我为这些行为编写的代码如下。但问题是将空数据保存到数据库中。
for (int i = 0; i < GridView1.Rows.Count; i++)
{
f_name = ((TextBox)GridView1.Rows[i].FindControl("TextBox1"));
l_name = ((TextBox)GridView1.Rows[i].FindControl("TextBox2"));
contacts = ((TextBox)GridView1.Rows[i].FindControl("TextBox3"));
string query = string.Format("insert into [StudentsData].[dbo].[Student_Info] values('{0}','{1}','{2}')",f_name.Text,l_name.Text,contacts.Text);
command.CommandText = query;
try
{
conn.Open();
command.ExecuteNonQuery();
}
finally
{
conn.Close();
}
}
答案 0 :(得分:0)
循环是这样的(和其他人一样,使用带参数的存储过程):
foreach (GridViewRow row in GridView1.Rows)
{
f_name = ((TextBox)row.FindControl("TextBox1")).Text;
//etc.
using (SqlConnection conn = new SqlConnection(yourConnectionString))
{
using (SqlCommand cmd = new SqlCommand("yourStoredProcedure", conn))
{
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@f_name", f_name);
//etc.
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
}
}
}