How to display specific database entries into a textbox on a WinForm application

后端 未结 3 1885
北荒
北荒 2021-02-06 19:39

UPDATE: Thanks everyone, the code was not the issue, although the information regarding SQL injection was useful, my issue was that I was using an older version of my database w

3条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-02-06 20:25

    you have SQL Injection problem with '" + textBox3.Text + "'"

    and you don't have to name your controls like that, you have to use a meaningful names

    you can use this code

    using (SqlConnection connection = new SqlConnection(@"Data Source=(LocalDB)\v11.0 AttachDbFilename=C:\Users\h8005267\Desktop\Practical Project\Build\System4\System\StockControl.mdf;Integrated Security=True;Connect Timeout=30"))
    {
        connection.Open();
        SqlCommand cmd = new SqlCommand("SELECT * FROM Product WHERE ProductID=@ProductID", connection);
        cmd.Parameters.AddWithValue("@ProductID", textBox3.Text);
        SqlDataReader re = cmd.ExecuteReader();
        if (re.Read())
        {
            textBox4.Text = re.GetString(re.GetOrdinal("ProductTitle")); // only fills using first product in table
            textBox5.Text = re.GetString(re.GetOrdinal("ProductPublisherArtist"));
            comboBox1.Text = re.GetString(re.GetOrdinal("ProductType"));
            textBox6.Text = re.GetString(re.GetOrdinal("Price"));
        }
        else
        {
            MessageBox.Show("Please enter a valid item barcode");
        }
        re.Close();
    }
    

提交回复
热议问题