我是 Windows 窗体和 SQL Server 的初学者,所以请原谅我糟糕的代码。我正在尝试根据表单上的字段更新我的 SQL 服务器上的数据。这是表格,
这是选择图像按钮单击事件代码,
String imgLocation = "";
private void btnInvChooseImg_Click(object sender, EventArgs e)
{
try
{
OpenFileDialog openFileDialog = new OpenFileDialog();
openFileDialog.Filter = "JPG Files (*.jpg)|*.jpg|PNG Files (*.png)|.png|All Files (*.*)|*.*";
openFileDialog.Title = "Select Product Image";
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
imgLocation = openFileDialog.FileName.ToString();
pbInvImg.ImageLocation = imgLocation;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
这是更新按钮点击事件代码,
private void btnUpdate_Click(object sender, EventArgs e)
{
con.Open();
try
{
if (txtProdName.Text != "" && txtProdDesc.Text != "" && txtQuantity.Text != "" && cmbAddCategory.Text != "" && pbInvImg.Image != null)
{
byte[] img = null;
FileStream fileStream = new FileStream(imgLocation, FileMode.Open, FileAccess.Read);
BinaryReader binaryReader = new BinaryReader(fileStream);
img = binaryReader.ReadBytes((int)fileStream.Length);
cmd = new SqlCommand(@"UPDATE PRODUCTS
SET ProductImage = @img,
ProductName = '" + txtProdName.Text
+ "', ProductDescription = '" + txtProdDesc.Text
+ "', Quantity = '" + txtQuantity.Text
+ "', CID = (SELECT CID FROM CATEGORY WHERE CategoryName = '" + cmbAddCategory.Text
+ "') WHERE PID = '" + lblProdID.Text + "';", con);
cmd.Parameters.Add(new SqlParameter("@img", img));
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("Product updated successfully.");
loadInventory();
clearFields();
}
else if (txtProdName.Text == "" || txtProdDesc.Text == "" || txtQuantity.Text == "" || cmbAddCategory.Text == "" || pbInvImg.Image == null)
{
MessageBox.Show("Please supply all fields.");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
如果我选择不同的图像,更新工作正常,但如果我只想更新/更改产品名称而不是图像,则会出现错误,提示错误路径名称不合法。知道我错过了什么吗?谢谢你。
