public static string SQLCONSTR = "Data Source=IE361-PC ;Initial Catalog=CSSTS;Integrated Security=SSPI;User ID=sa;Password=xj;Connect Timeout=20";
{
//新建數據連接
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>"); //提示信息並關閉本頁面定位到另一個頁面
}
}
頁面運行效果 :