2012-01-18 63 views
0

我只有一列的gridview。我已经写了这样的代码如何将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控件有两行,然后第一行存储在数据库中的两倍。如果gridview有3行,那么第一行将被存储三次。我该如何解决这个问题?

+0

你可能想要做在做太多之前搜索“.Net数据绑定”。你可能会发现一些你想要的东西...... – 2012-01-18 22:15:43

+0

你应该检查代码中的“e.ItemType”。 – Praveen 2012-01-18 22:18:48

回答

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; 

你可能还需要检查仅用于数据行让你的操作不会对页脚/标题行等发生

新代码:

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(); 
    } 
} 
相关问题