将gridview的所有行保存到数据库asp.net c#

时间:2017-04-15 13:04:26

标签: c# asp.net sql-server gridview

我有一个带有两列的gridview,其中一列是带有下拉列表的模板字段。我想用gridview外面的保存按钮将所有行保存到数据库中,但是当我点击它时只保存第一行gridview ..如何将整个gridview保存到数据库?

protected void Button1_Click(object sender, EventArgs e)
        {

            for (int i = 0; i < GridView2.Rows.Count; i++)
            {

                    GridViewRow row = GridView2.Rows[i];

                    string coursecode = DropDownList1.SelectedValue.ToString();
                    string weekno = DropDownList2.SelectedValue.ToString();
                    string day = DropDownList3.SelectedValue;
                    string stid = row.Cells[0].Text;
                    DropDownList ddlstatus = (DropDownList)row.Cells[1].FindControl("DropDownList9");
                    string status = ddlstatus.SelectedValue.ToString();

                    double percentage;
                    if (status == "A")
                    {
                        if (day == "Saturday")
                        {
                            percentage = 6.66;
                        }
                        else
                        {
                            percentage = 3.33;
                        }
                    }
                    else
                    {
                        percentage = 0;
                    }


                    String strConnString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
                    SqlConnection con = new SqlConnection(strConnString);
                    String query = "insert into Attendance values (@CourseCode, @St_ID, @WeekNo, @Day,@Status, @Percentage)";
                    SqlCommand cmd = new SqlCommand(query, con);
                    cmd.Parameters.AddWithValue("@CourseCode", coursecode);
                    cmd.Parameters.AddWithValue("@WeekNo", weekno);
                    cmd.Parameters.AddWithValue("@Day", day);
                    cmd.Parameters.AddWithValue("@St_ID", stid);
                    cmd.Parameters.AddWithValue("@Status", status);
                    cmd.Parameters.AddWithValue("@Percentage", percentage);
                    con.Open();
                    cmd.ExecuteNonQuery();
                    con.Close();
                    Response.Redirect("~/DoctorAddEditAttendance.aspx");
                }
            }

1 个答案:

答案 0 :(得分:1)

Redirect移到循环外部,以便完成所有行的处理。

顺便提一下,最好以这种方式重定向:

Response.Redirect("~/DoctorAddEditAttendance.aspx", false);
Context.ApplicationInstance.CompleteRequest();