首页 > 解决方案 > 如何将传递的值添加到数据库?

问题描述

我正在用 ASP.NET C# 练习 WebApplication

我已经在该页面中创建了产品页面我已经使用来自数据库的数据创建了 gridview,而且每一行中都有一个名为 Edit 的按钮。它将带您使用该行数据更新页面。它会将值相应地放在文本框中。

产品页面图片

更新页面中有文本字段和下拉框,但是当我更改数据并单击更新按钮时,数据库中的数据不会更新。

编辑页面的图像

产品.aspx

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace WebApplication5.Product
{
    public partial class Product1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
        {
            string pid = GridView1.SelectedRow.Cells[0].Text;
            Response.Redirect("UpdateProduct.aspx?Product_ID=" + pid);
        }
    }
}

更新产品.aspx

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.Data.Sql;
using System.Configuration;

namespace WebApplication5.Product
{
    public partial class UpdateProduct : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ToString());
          String myquery = "Select * from Product where pro_id=" + Request.QueryString["Product_ID"];
            SqlConnection con = new SqlConnection(mycon);
            SqlCommand cmd = new SqlCommand();
            cmd.CommandText = myquery;
            cmd.Connection = con;
            SqlDataAdapter da = new SqlDataAdapter();
            da.SelectCommand = cmd;
            DataSet ds = new DataSet();
            da.Fill(ds);
            if (ds.Tables[0].Rows.Count > 0)
            {
                txtpid.Text = ds.Tables[0].Rows[0]["pro_id"].ToString();
                txtpname.Text = ds.Tables[0].Rows[0]["pro_name"].ToString();

                txtpprice.Text = ds.Tables[0].Rows[0]["pro_price"].ToString();
                txtpq.Text = ds.Tables[0].Rows[0]["pro_qty"].ToString();
            }
            con.Close();
        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            SqlConnection con1 = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ToString());
            con1.Open();
            string sql ="UPDATE Product set pro_name='"+txtpname.Text.ToString()+"',cat_name='"+DropDownList1.SelectedValue.ToString()+"',pro_price='"+txtpprice.ToString()+"',pro_qty='"+txtpq.ToString()+"'where pro_id='"+txtpid.Text.ToString()+"'";
            SqlCommand cmd1 = new SqlCommand(sql,con1);
            cmd1.ExecuteNonQuery();
            Response.Write("Updated!");

        }

    }
}

标签: c#asp.netwebformsado.net

解决方案


请使用 SQLcatch(SqlException ex) 进行 try catch 块,并尝试使用属性。您在 MSSQL 中也有很好的工具,它被称为“SQL 服务器分析器”。


推荐阅读