从文本字段插入到表-空字段
本文关键字:字段 插入 文本 | 更新日期: 2023-09-27 17:57:35
我遇到了一些问题:下面的代码用新行更新了表,但这一行中的所有字段都是空的。我想将文本字段中的输入数据放到Members表中的新行中。
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.Web.Configuration;
public partial class Default4 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
txtFirstName.Text = "";
txtLastName.Text = "";
txtAdress.Text = "";
txtResidence.Text = "";
txtEmail.Text = "";
}
protected void btnRegister_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(
WebConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
SqlCommand cmd = new SqlCommand("INSERT INTO Members(FirstName, LastName, Adress, Residence, Email) VALUES (@txtFirstName, @txtLastName, @txtAdress, @txtResidence, @txtEmail)", con);
cmd.Parameters.AddWithValue("@txtFirstName", txtFirstName.Text);
cmd.Parameters.AddWithValue("@txtLastName", txtLastName.Text);
cmd.Parameters.AddWithValue("@txtAdress", txtAdress.Text);
cmd.Parameters.AddWithValue("@txtResidence", txtResidence.Text);
cmd.Parameters.AddWithValue("@txtEmail", txtEmail.Text);
try
{
con.Open();
cmd.ExecuteNonQuery();
lblConfirm.Text = "Database updated, insert confirmed!";
txtFirstName.Text = "";
txtLastName.Text = "";
txtAdress.Text = "";
txtResidence.Text = "";
txtEmail.Text = "";
}
finally
{
con.Close();
}
}
}
如果我更改此行:
SqlCommand cmd = new SqlCommand("INSERT INTO Members(FirstName, LastName, Adress, Residence, Email) VALUES (@txtFirstName, @txtLastName, @txtAdress, @txtResidence, @txtEmail)", con);
类似的东西:
SqlCommand cmd = new SqlCommand("INSERT INTO Members(FirstName, LastName, Adress, Residence, Email) VALUES ('@txtFirstName', '@txtLastName', @txtAdress, @txtResidence, @txtEmail)", con);
它将打印出一行,其中包含如下字段:|@txtFirst名称|@txtLastName |[Empty]|[Empty]|[Eempty]|
任何帮助都将是伟大的,谢谢!
每次按下注册按钮时,都会执行Page_Load
,清空文本框,然后执行btnRegister_Click
。此时,您的文本框为空白。
您需要在Page_Load事件中添加一个检查
if(!IsPostBack)
{
... // code to empty the textboxes
}
第页。MSDN 上的IsPostBack属性
这是问题。。。。
try
{
con.Open();
cmd.ExecuteNonQuery();
lblConfirm.Text = "Database updated, insert confirmed!";
txtFirstName.Text = "";
txtLastName.Text = "";
txtAdress.Text = "";
txtResidence.Text = "";
txtEmail.Text = "";
}
^^^^^^重置此处的所有字段不会有任何区别。它将在每次回发后发生。
试试这个
if(!IsPostBack)
{
txtFirstName.Text = "";
txtLastName.Text = "";
txtAdress.Text = "";
txtResidence.Text = "";
txtEmail.Text = "";
}
因此,单击按钮时,用户输入不会重置为零。。
这里有更好的方法来实现你的目标。。。