我正在尝试将表单中的填充信息提交到数据库。我已经为保存按钮完成了下面提到的编码。当我单击保存按钮以保存信息时,我收到错误。我需要它完成,同样需要来自这里的极客的帮助。
来自数据库的SAVE按钮数据的COED
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string conn = ConfigurationManager
.ConnectionString("welcome").ConnectionString;
SqlConnection con=new SqlConnection(conn);
SqlCommand cmd = new SqlCommand("Insert into abhishek(pr_name,Add,add2) values(@ah,@Ap,@qe)",con);
cmd.CommandType = CommandType.Text;
cmd.Parameter.Addwithvalue("@ah", TextBox1.Text.Trim());
cmd.Parameter.Addwithvalue("@ap", TextBox2.Text.Trim());
cmd.Parameter.Addwithvalue("@qe", TextBox3.Text.Trim());
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
检查下图中的错误:
答案 0 :(得分:0)
您错过了ConnectionStrings
索引属性中的's'。但是,一旦你修复了这个错误,你也会发现你错过了SqlCommand.Parameters
属性的更多'。
要揭示这些问题,请打开代码隐藏文件的“属性”,然后选择“编译的构建操作”。 (另外,我可以从您的图像中看到,您的项目看起来像是一个Web站点而不是Web应用程序;如果可能的话,请考虑将其转换为Web应用程序,因为它提供了许多好处。)< / p>
一旦纠正了语法,就应该更改代码,以便通过按钮单击处理程序而不是页面加载来调用更新。
在aspx中的标记代码中:
<asp:Button runat="server" ID="btnSave" Text="Save" OnClick="btnSave_Click" />
在您的代码隐藏中:
protected void btnSave_Click(object sender, EventArgs e)
{
string conn = ConfigurationManager.ConnectionStrings["welcome"].ConnectionString;
using (SqlConnection con = new SqlConnection(conn))
{
SqlCommand cmd = new SqlCommand("Insert into abhishek(pr_name,Add,add2) values(@ah,@Ap,@qe)", con);
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("@ah", TextBox1.Text.Trim());
cmd.Parameters.AddWithValue("@ap", TextBox2.Text.Trim());
cmd.Parameters.AddWithValue("@qe", TextBox3.Text.Trim());
con.Open();
cmd.ExecuteNonQuery();
}
}
请注意,我已将代码移动到按钮单击事件处理程序中,并将移出 Page_Load。 Load事件处理程序只应用于页面执行路径上无条件所需的初始化项目(即,无论页面上点击了什么按钮),都应如下所示:
protected void Page_Load(object sender, EventArgs e)
{
// Code to run every time the page is created, both initially and on postback
if (IsPostBack)
{
// Code to run every time the page is posted back (any submit event)
}
else
{
// Code to run on the initial creation of the page
}
}