using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
public partial class Details : System.Web.UI.Page
{
string strcon = ConfigurationManager.ConnectionStrings["con"].ConnectionString;
string objective = " ";
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(strcon);
if (con.State == ConnectionState.Closed)
{
con.Open();
}
{
String SQL = "SELECT TOP 2 * FROM QuestionBank ORDER BY NEWID()";
SqlDataAdapter Adpt = new SqlDataAdapter(SQL, con);
DataSet login1 = new DataSet();
Adpt.Fill(login1);
foreach (DataRow dr in login1.Tables[0].Rows)
{
objective = login1.Tables[0].Rows[0]["s_id"].ToString() + "," + login1.Tables[0].Rows[1]["s_id"].ToString();
Label1.Text = login1.Tables[0].Rows[0]["question"].ToString();
Label2.Text = login1.Tables[0].Rows[0]["question"].ToString();
break;
}
}
}
protected void Button1_Click(object sender, EventArgs e))
{
SqlConnection con = new SqlConnection(strcon);
if (con.State == ConnectionState.Closed)
{
con.Open();
}
SqlCommand cmd = new SqlCommand("Insert into PaperTbl values('" + objective + "','" + TextBox1.Text + "','" + TextBox2.Text + "')", con);
cmd.ExecuteNonQuery();
Response.Write("<script>alert('Answers Saved Successfully');location.href='Details.aspx'</script>");
}
}
当我单击“保存”按钮时 然后Label1和Label2中的问题得到更改 因此,来自textbox1和textbox2的答案变得错误。 因此,在保存数据时,将刷新并保存新问题而不是旧问题。请帮助我。
答案 0 :(得分:0)
Page_Load 正在运行,您的 TextBox1_TextChanged 回发事件之前。因此,将填充新值,然后保存。
请参见此处以了解页面生命周期https://www.c-sharpcorner.com/UploadFile/8911c4/page-life-cycle-with-examples-in-Asp-Net/
这应该有效:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
LoadNew();
}
}
private void LoadNew()
{
string strcon = ConfigurationManager.ConnectionStrings["con"].ConnectionString;
string objective = " ";
SqlConnection con = new SqlConnection(strcon);
if (con.State == ConnectionState.Closed)
{
con.Open();
}
{
String SQL = "SELECT TOP 2 * FROM QuestionBank ORDER BY NEWID()";
SqlDataAdapter Adpt = new SqlDataAdapter(SQL, con);
DataSet login1 = new DataSet();
Adpt.Fill(login1);
foreach (DataRow dr in login1.Tables[0].Rows)
{
objective = login1.Tables[0].Rows[0]["s_id"].ToString() + "," + login1.Tables[0].Rows[1]["s_id"].ToString();
Label1.Text = login1.Tables[0].Rows[0]["question"].ToString();
Label2.Text = login1.Tables[0].Rows[0]["question"].ToString();
break;
}
}
}
protected void TextBox1_TextChanged(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(strcon);
if (con.State == ConnectionState.Closed)
{
con.Open();
}
SqlCommand cmd = new SqlCommand("Insert into PaperTbl values('" + objective + "','" + TextBox1.Text + "','" + TextBox2.Text + "')", con);
cmd.ExecuteNonQuery();
LoadNew();
Response.Write("<script>alert('Answers Saved Successfully');location.href='Details.aspx'</script>");
}