在另一个文本框中输入数据时,将SQL Server表中的数据添加到文本框中

时间:2019-04-03 03:32:07

标签: c# asp.net sql-server visual-studio

这是我的程序:

Program

我想做什么:当我在1文本框中输入ProductID时,我想要category的{​​{1}},nameprice填充到他们的文本框中。

我尝试从产品表ProductID = 1中读取内容,然后更改其他文本框以在其他列中显示数据

当我更改ProductID文本框时,这是我的代码:

ProductID = ProductIDTB.Text

解决方法:由于textbox_textchanged事件不起作用,我决定添加一个使用ID查找产品的按钮:

protected void ProductIDTB_TextChanged(object sender, EventArgs e)
{
        string connectionString1;
        SqlConnection cnn1;

        connectionString1 = "Data Source=(localdb)\\MSSQLLocalDB;Initial Catalog=Greenwich_Butchers;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False";
        cnn1 = new SqlConnection(connectionString1);

        string selectSql1 = "SELECT * FROM [Product] WHERE ProductID = ('" + Convert.ToInt32(ProductIDTB.Text) + "') ";

        SqlCommand com1 = new SqlCommand(selectSql1, cnn1);

        try
        {
            cnn1.Open();

            using (SqlDataReader read = com1.ExecuteReader())
            {
                while (read.Read())
                {
                    String productcategory = Convert.ToString(read["ProductCategory"]);
                    ProductCategoryTB.Text = productcategory;
                    String productname = Convert.ToString(read["ProductName"]);
                    ProductNameTB.Text = productname;
                    String productprice = Convert.ToString(read["ProductPrice"]);
                    ProdPriceTB.Text = productprice;
                }
            }
        }
        catch (Exception ex)
        {
            Response.Write("error" + ex.ToString());
        }
        finally
        {
            cnn1.Close();
        }
    }

2 个答案:

答案 0 :(得分:2)

将文本框的AutoPostBack属性设置为true

更多信息:https://meeraacademy.com/textbox-autopostback-and-textchanged-event-asp-net/

<asp:TextBox ID="ProductIDTB" runat="server" AutoPostBack="True" 
OnTextChanged="ProductIDTB_TextChanged"></asp:TextBox>

顺便说一句,使用SqlParameter来使用参数化查询。除了防止SQL注入攻击,参数化查询还可以帮助RDBMS存储和重用类似查询的执行计划,以确保更好的性能。参见:https://dba.stackexchange.com/questions/123978/can-sp-executesql-be-configured-used-by-default

string selectSql1 = "SELECT * FROM [Product] WHERE ProductID = @productIdFilter";

int productIdFilter = Convert.ToInt32(ProductIDTB.Text);

SqlCommand com1 = new SqlCommand(selectSql1, cnn1);
com1.Parameters.AddWithValue("productIdFilter", productIdFilter);

答案 1 :(得分:0)

代码背后的OnTextChanged事件

protected void txtProductId_TextChanged(object sender, EventArgs e) 
{
    SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["_connect"].ToString());

    int ProductId = Convert.ToInt32(txtProductId.Text);

    SqlCommand com = con.CreateCommand();
    com.CommandText = "sp_ProductGetData";
    com.CommandType = CommandType.StoredProcedure;

    com.Parameters.AddWithValue("@Mode", 1);
    com.Parameters.AddWithValue("@ProductId", ProductId);   

    con.Open();

    SqlDataReader dr = com.ExecuteReader();

    if (dr.HasRows)
    {
        dr.Read();
        txtProductCategory.Text = Convert.ToString(dr["ProductCategory"]);
        txtProductName.Text = Convert.ToString(dr["ProductName"]);
        txtPrice.Text = Convert.ToString(dr["Price"]);
    }  
    else
    {
        ScriptManager.RegisterClientScriptBlock((Page)(HttpContext.Current.Handler), typeof(Page), "alert", "javascript:alert('" + Convert.ToString(("No Record Found with Prodcut Id: "+ProductId)) + "');", true);
        return;
    }

    con.Close();
}

存储过程

CREATE PROCEDURE sp_ProductGetData
(
  @Mode INT=NULL,
  @ProductId INT=NULL   
)
AS
BEGIN   
  IF(@Mode=1)
  BEGIN
    SELECT ProductCategory,ProductName,Price FROM Product
    WHERE ProductId=@ProductId
  END       
END