数据库不会将信息全部存储在同一行上。在第一页上,当我点击按钮时,它会将其记录下来并且很好,它已经存储了。然后在下一页,当我点击按钮时,它存储信息,但在另一行?有解决方案吗下面是问题,下面是代码。
第1页
public void addInformationToDatabase()
{
string Sex = ddlGender.Text;
string Name = tbxName.Text;
string DOB = tbxDOB.Text;
string connectionString = WebConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
SqlConnection Con = new SqlConnection(connectionString);
SqlCommand command = new SqlCommand();
command.Connection = Con;
command.CommandType = CommandType.Text;
command.CommandText = "INSERT INTO [User] (GenderID,Name,DOB) VALUES(@Sex,@Name,@DOB)";
command.Parameters.AddWithValue("@Sex", Sex);
command.Parameters.AddWithValue("@Name", Name);
command.Parameters.AddWithValue("@DOB", DOB);
try
{
Con.Open();
command.ExecuteNonQuery();
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
finally
{
Con.Close();
}
}
2ND PAGE
public void save()
{
string checkboxSelection = CheckBoxList1.SelectedItem.ToString();
string connectionString = WebConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
SqlConnection Con = new SqlConnection(connectionString);
SqlCommand c = new SqlCommand();
c.Connection = Con;
c.CommandType = CommandType.Text;
c.CommandText = "INSERT INTO [User] (Ans1) VALUES(@Ans1)";
c.Parameters.AddWithValue("@Ans1", checkboxSelection);
try
{
Con.Open();
c.ExecuteNonQuery();
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
finally
{
Con.Close();
}
}
感谢任何帮助
答案 0 :(得分:1)
您的第一页需要在插入后获取ID,然后您的第二页需要根据该ID执行update,而不是后续插入。
有许多关于获取ID的资源 - 例如How to get last inserted id?
(我假设id字段唯一标识你的行)
第一次查询 -
c.CommandText = "INSERT INTO [User] (Ans1) VALUES(@Ans1); SELECT SCOPE_IDENTITY()";
...
int userID = (Int32) c.ExecuteScalar();
您需要将该ID传递到第二页并将插入更改为更新:
"UPDATE User] SET Ans1 = @Ans1 WHERE Id = @id";
您还需要将id添加为参数
c.Parameters.AddWithValue("@id", userID);