在VS後臺接收GridView中綁定的數據


將一個數據庫表中的數據取出並通過gridview顯示出來,然後將某一列的數據插入到另一張數據庫表中
(此例的兩個數據庫分別爲exam,test_table)

//數據庫連接字符串
 public static string SQLCONSTR = "Data Source=IE361-PC ;Initial Catalog=CSSTS;Integrated Security=SSPI;User ID=sa;Password=xj;Connect Timeout=20";


 protected void Button2_Click(object sender, EventArgs e)
    {
        //新建數據連接
        SqlConnection conn = new SqlConnection(SQLHelper.SQLCONSTR);
        SqlCommand cmd = new SqlCommand();
         conn.Open();
        cmd.Connection = conn;
        string Strsql = string.Empty;
        cmd.CommandText = "select username from users where username='" + this.TextBox1.Text.ToString().Trim() + "'";
        SqlDataReader sr = cmd.ExecuteReader();
        if (sr.Read() == false)
        {  
            Response.Write("<script>alert(\"您輸入的用戶名不存在!\");</script>");
            conn.Close();
        }        
        else
        {
            conn.Close();
            bool result;
            double score=0.0;
            conn.Open();
            for (int i = 0; i < this.GridView1.Rows.Count; i++)                           //獲取gridview中某幾列的數據
            {                
                string ZID = GridView1.Rows[i].Cells[0].Text.Trim().ToString();
                string NID = GridView1.Rows[i].Cells[1].Text.Trim().ToString();
                CheckBox rb = GridView1.Rows[i].FindControl("CheckBox1") as CheckBox; //gridview裏的bit字段會自動成爲checkbox
                if (rb.Checked)
                {
                    result = true;
                    cmd.CommandText = "SELECT score FROM exam WHERE ZID='" + ZID + "'AND NID= '" + NID + "'";
                    SqlDataReader sdr = cmd.ExecuteReader();
                    sdr.Close();
                    score = Convert.ToDouble(cmd.ExecuteScalar());                    
                }
                else
                {
                    result = false;
                    score = 0;
                }
                string test_user = this.TextBox1.Text.ToString().Trim();
                System.DateTime currentTime = new System.DateTime();

                currentTime = System.DateTime.Now;                //取當前年月日時分秒 

                Strsql = "Insert Into test_table (ZID, NID, test_user, testtime, result,score) VALUES ('" + ZID + "', '" + NID + "','" + test_user + "','" + currentTime + "','" + result + "','"+ score + "')";
                cmd.CommandText = Strsql;
                cmd.ExecuteNonQuery();                
            }
            conn.Close();
            Response.Write("<script>alert(\"添加成功!\");location.href=\"user.aspx\";</script>");    //提示信息並關閉本頁面定位到另一個頁面
        }
    }


頁面運行效果 :



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章