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

需求:将Gridview中的数据直接导入到数据苦中对应的学科表中.

界面:导入到总表:

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"/>


界面执行结果:

数据库执行结果:

 

 

  • 2
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值