如何将gridview内容存储到数据库表中

时间:2012-01-18 22:14:02

标签: c#

我只有一列的gridview。我写了像

这样的代码
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        SqlConnection con = new SqlConnection(strConnString); 
        con.Open();

        for (int i = 0; i < GridView1.Rows.Count; i++)
       {
            string Users = GridView1.Rows[i].Cells[0].Text;

            string strQuery = "insert into Table1 (FileName, DateTimeUploaded, Type, Username)" +
            " values(@FileName, @DateTimeUploaded, @Type, @Username)";
            SqlCommand cmd = new SqlCommand(strQuery);

            cmd.Parameters.AddWithValue("@FileName", datalink);
            cmd.Parameters.AddWithValue("@Type", ext);
            cmd.Parameters.AddWithValue("@DateTimeUploaded", DateTime.Now);
            cmd.Parameters.AddWithValue("@Username", Users);

            cmd.CommandType = CommandType.Text;
            cmd.Connection = con;
            cmd.ExecuteNonQuery();

       }
        con.Close();
        con.Dispose();

          }

如果此gridview有2行,则第一行存储在数据库中两次。如果gridview有3行,则第一行存储三次。我该如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

<强>解释

您正在将数据插入到GridView的RowDataBound事件中的数据库中 - 每次绑定DataRow时都会执行此操作!这个以及你使用以下每个时间遍历每行的事实:

 for (int i = 0; i < GridView1.Rows.Count; i++)  { // inserting record from each row }

表示在绑定更多行时,您的行将被多次插入。您需要删除for循环,然后使用e.Row.Cells[0]来引用并仅插入当前绑定的行数据。

 string Users = e.Row.Cells[0].Text; 

您可能还想检查DataRows,以便在页脚/标题行等上不会发生操作。

新代码:

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e) 
{ 
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        SqlConnection con = new SqlConnection(strConnString);  
        con.Open(); 

        string Users = e.Row.Cells[0].Text; // current row being bound

        string strQuery = "insert into Table1 (FileName, DateTimeUploaded, Type, Username)" + 
        " values(@FileName, @DateTimeUploaded, @Type, @Username)"; 
        SqlCommand cmd = new SqlCommand(strQuery); 

        cmd.Parameters.AddWithValue("@FileName", datalink); 
        cmd.Parameters.AddWithValue("@Type", ext); 
        cmd.Parameters.AddWithValue("@DateTimeUploaded", DateTime.Now); 
        cmd.Parameters.AddWithValue("@Username", Users); 

        cmd.CommandType = CommandType.Text; 
        cmd.Connection = con; 
        cmd.ExecuteNonQuery(); 

        con.Close(); 
        con.Dispose(); 
     }
 }