我有一个表单,用户可以注册必填字段,并且可以选择在其桌面上浏览图像。我没有将实际图像保存在数据库中。我使用了Openfile对话框,当用户选择图像时,它将路径复制到标签,所选图像将保存在我的项目文件夹中,并且路径将保存在数据库中。现在的问题是,如果用户不想拥有一张图片该怎么办?为了解决此问题,我使用资源以编程方式将图片设置到了我的图片框。这是现在的问题,我如何获取图片框的图像路径(图像位于资源中)并将其复制到标签中,还可以看到我具有File.Copy功能,我不希望在以下情况下启用此代码用户未选择任何图像。
PS:如果没有上传的图片,则为默认图片,例如facebook
public partial class RegisterCustomer : UserControl
{
public RegisterCustomer()
{
InitializeComponent();
UserImage.Image = Properties.Resources.User;
//var img = Image.FromFile(@"C:\Users\dieth\source\repos\SalesInventoryManagement\SalesInventoryManagement\bin\Debug\Icons\User.png");
//UserImage.Image = img;
}
Register rc = new Register();
private void Btn_Register_Click(object sender, EventArgs e)
{
File.Copy(lbl_location.Text, Path.Combine(@"C:\Users\dieth\source\repos\SalesInventoryManagement\SalesInventoryManagement\bin\Picture", Path.GetFileName(lbl_location.Text)), true);
rc.Insert(lbl_location.Text, string.Format(txt_firstname.Text + " " + txt_middlename.Text + " " + txt_lastname.Text), cbox_gender.Text, txt_contact.Text, txt_email.Text, txt_address.Text, Variables.Current_Date);
MessageBox.Show("Successfully Added", "System Message:", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1);
}
private void Btn_Browse_Click(object sender, EventArgs e)
{
rc.BrowseImage(UserImage, Variables.location , lbl_location);
}
}
public class Register
{
public void Insert(string path, string Fullname, string Gender, string Contact_Number, string Email, string Home_Address, string Dates)
{
using (var con = new SqlConnection(ConfigurationManager.ConnectionStrings["SalesInventoryManagement.Properties.Settings.Setting"].ConnectionString))
{
using (var cmd = new SqlCommand("usp_InsertCustomer", con))
{
con.Open();
byte[] b = File.ReadAllBytes(path);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("@Images", SqlDbType.VarChar).Value = path;
cmd.Parameters.Add("@Full_Name", SqlDbType.VarChar, 50).Value = Fullname;
cmd.Parameters.Add("@Gender", SqlDbType.VarChar, 50).Value = Gender;
cmd.Parameters.Add("@Contact_Number", SqlDbType.VarChar, 11).Value = Contact_Number;
cmd.Parameters.Add("@Email", SqlDbType.VarChar, 50).Value = Email;
cmd.Parameters.Add("@Home_Address", SqlDbType.VarChar, 50).Value = Home_Address;
cmd.Parameters.Add("@Dates", SqlDbType.Date).Value = Dates;
cmd.ExecuteNonQuery();
con.Close();
}
}
}
public void BrowseImage(PictureBox UserImage, string location, Label path)
{
using (OpenFileDialog ofd = new OpenFileDialog())
{
ofd.Filter = "Image Files (*.jpg;*.jpeg;.*.png; | *.jpg;*.jpeg;.*.png;)";
ofd.FilterIndex = 1;
ofd.Multiselect = false;
ofd.Title = "Select Image File";
if (ofd.ShowDialog() == DialogResult.OK)
{
location = ofd.FileName;
path.Text = location;
UserImage.Image = Image.FromFile(location);
UserImage.SizeMode = PictureBoxSizeMode.StretchImage;
}
}
}
答案 0 :(得分:0)
您可以使用以下命令获取资源路径。
var path = Path.GetFullPath(Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory,
@"..\..\Resources","User.png"));