繁体   English   中英

保存连接到数据库的按钮代码在ASP.NET中不起作用

[英]Save button code connecting to database not working in ASP.NET

我正在尝试将表单中的填充信息提交给数据库。 我已经为保存按钮完成了下面提到的编码。 当我单击“保存”按钮以保存信息时,出现错误。 我需要做到这一点,并且同样需要来自这里的极客的帮助。

从数据库保存按钮数据的编码

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();
    }
}

检查下图中的错误:

在此处输入图片说明

您缺少ConnectionStrings索引属性中的“ s”。 但是,一旦修复了该错误,您还将发现SqlCommand.Parameters属性缺少更多的“ s”。

要揭示这些问题,请打开代码隐藏文件的“属性”,然后选择“生成编译操作”。 (此外,我从您的图像中可以看到,您的项目看起来像是设置为网站而不是Web应用程序;如果可能,请考虑将其转换为Web应用程序,因为它有很多好处。)

一旦纠正了语法,就应该更改代码,以便通过按钮单击处理程序而不是在页面加载时调用更新。

在您的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
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM