Ниже этого кода находится моя кнопка Добавить в моей форме окна. Когда я пытался щелкнуть по нему без добавления какого-либо изображения и без пути, также произошла ошибка, о которой я упоминал под этим кодом. Я хочу исправить это исключение, даже если пользователь не добавляет изображение или путь к файлу, он не получает исключение. Я знаю, что об этом спрашивали много раз, но их исключения в коде отличаются, поэтому я немного запутался. Спасибо
private void btn_add_Click(object sender, EventArgs e)
{
byte[] image = null;
var stream = new FileStream(this.txt_path.Text, FileMode.Open, FileAccess.Read);
var read = new BinaryReader(stream);
image = read.ReadBytes((int)stream.Length);
using (var con = SQLConnection.GetConnection())
{
if (string.IsNullOrEmpty(cbox_supplier.Text) || string.IsNullOrEmpty(txt_code.Text) || string.IsNullOrEmpty(txt_item.Text) || string.IsNullOrEmpty(txt_quantity.Text) || string.IsNullOrEmpty(txt_cost.Text) || string.IsNullOrEmpty(txt_path.Text))
{
MetroMessageBox.Show(this, "Please input the Required Fields", "System Message:", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
else
{
var selectCommand = new SqlCommand("Insert into employee_product (Image, Supplier, Codeitem, Itemdescription, Date, Quantity, Unitcost) Values (@Image, @Supplier, @Codeitem, @Itemdescription, @Date, @Quantity, @Unitcost)",con);
selectCommand.Parameters.AddWithValue("@Image", image);
selectCommand.Parameters.AddWithValue("@Supplier", cbox_supplier.Text);
selectCommand.Parameters.AddWithValue("@Codeitem", txt_code.Text.Trim());
selectCommand.Parameters.AddWithValue("@Itemdescription", txt_item.Text.Trim());
selectCommand.Parameters.AddWithValue("@Date", txt_date.Text.Trim());
selectCommand.Parameters.AddWithValue("@Quantity", txt_quantity.Text.Trim());
selectCommand.Parameters.AddWithValue("@Unitcost", txt_cost.Text.Trim());
selectCommand.ExecuteNonQuery();
MessageBox.Show("Added successfully", "SIMS", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1);
txt_path.Clear();
pictureBox1.Image = null;
txt_code.Clear();
txt_item.Clear();
txt_quantity.Clear();
txt_cost.Clear();
_view.AddingProduct();
}
}
}
private void btn_upload_Click(object sender, EventArgs e)
{
OpenFileDialog opnfd = new OpenFileDialog();
opnfd.Filter = "Image Files (*.jpg;*.jpeg;.*.gif;*.png;)|*.jpg;*.jpeg;.*.png;*.gif";
opnfd.Title = "Select Item";
if (opnfd.ShowDialog() == DialogResult.OK)
{
var path = opnfd.FileName.ToString();
txt_path.Text = path;
pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage;
pictureBox1.Image = Image.FromFile(opnfd.FileName);
}
}
// Здесь происходит исключение системного аргумента
byte[] image = null;
-----> var stream = new FileStream(this.txt_path.Text, FileMode.Open, FileAccess.Read);
var read = new BinaryReader(stream);
image = read.ReadBytes((int)stream.Length);