WEB开发网
开发学院WEB开发ASP.NET 如何将GridView中的数据导入到数据库 阅读

如何将GridView中的数据导入到数据库

 2012-09-18 13:32:43 来源:WEB开发网   
核心提示: 界面:导入到总表: protected void btnExportToMaster_Click(object sender, EventArgs e) { //连接字串"sqlConnString" string sqlConnStr

 界面:导入到总表:

 
 
protected void btnExportToMaster_Click(object sender, EventArgs e)
        {
            //连接字串"sqlConnString" 
            string sqlConnString = "";
            sqlConnString = System.Configuration.ConfigurationManager.ConnectionStrings["sqlconn"].ToString();
            SqlConnection con = new SqlConnection(sqlConnString);
            con.Open();
            //配置文件读取examID
            string examID = System.Configuration.ConfigurationManager.AppSettings["examID"];
            //根据examID考试号决定汇总到对应科目的表中
            string tbName = System.Configuration.ConfigurationManager.AppSettings[examID];
            //事物
            SqlTransaction tran = con.BeginTransaction();
            try
            {
                for (int i = 0; i < GVScore.Rows.Count; i++)
                {
                    string sqlStr = "";
                    SqlCommand comm = new SqlCommand(sqlStr, con);
                    string strExamId = GVScore.Rows[i].Cells[1].Text.Trim().ToString();

                    //获取HyperLink1中StudentId值
                    HyperLink href = (HyperLink)GVScore.Rows[i].Cells[2].FindControl("HyperLink1");
                    string strStudentId = href.Text;
                     

                    //如果是超链接只能获取空字符串
                    //HyperLink hl=(HyperLink)GVScore.FindControl ("HyperLink1");
                    //string strStudentId = hl.Text.ToString (); 

                    string strStudentName = GVScore.Rows[i].Cells[3].Text.Trim().ToString();
                    string  StudentScore = GVScore.Rows[i].Cells[4].Text.Trim().ToString();

                    sqlStr = "INSERT  " + tbName + "(examId,StudentName,StudentId,StudentScore) VALUES ('" + strExamId + "','" + strStudentId  + "','" + strStudentName + "','"+StudentScore +"')";

                    comm.CommandText = sqlStr;
                    comm.Connection = con;
                    comm.Transaction = tran;
                    comm.ExecuteNonQuery();
                }
                tran.Commit();
                Response.Write("<script>alert('导入成功!请勿重复导入!');</script>");
            }
            catch (Exception ex)
            {
                Response.Write("更新失败,失败原因:" + ex.Message);
                tran.Rollback();//事务回滚
            }
            finally
            {
                con.Close();
            }
        }
 
 
配置文件:
 
 
	  <!--考试号-->
    <!--43表示VB-->
	  <add key="examId" value="43"/>
    <!--考试号对应的总表-->
    <add key ="43" value="t_VB_ALLStudent_Scores"/>

1 2  下一页

Tags:如何 GridView 数据

编辑录入:爽爽 [复制链接] [打 印]
赞助商链接