简体   繁体   中英

uploading images in winforms application

Does anyone know if a there is a control to allow the user to upload a image to a windows form? Or any example code to accomplish this.

I am using win-form applications

Thanks,

To allow users to select files in a Windows Forms application you should look into using the OpenFileDialog class.

To use the dialog on your form you will need to find it in the toolbox in Visual Studio and drag it on to your form.

Once associated with the form you can then invoke the dialog from your code like so:

if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
    string selectedFile = openFileDialog1.FileName;
}

You can then use the file path to perform whatever task you wish with the file.

Note: You can use the FileDialog.Filter Property to limit the type of file extensions (images in your case) the user can select when using the dialog.

OpenFileDialog open = new OpenFileDialog();
open.Filter = "Image Files(*.jpeg;*.bmp;*.png;*.jpg)|*.jpeg;*.bmp;*.png;*.jpg";
if (open.ShowDialog() == DialogResult.OK)
{
    textBox10.Text = open.FileName;
}
cn.Open();
string image = textBox10.Text;
Bitmap bmp = new Bitmap(image);
FileStream fs = new FileStream(image, FileMode.Open, FileAccess.Read);
byte[] bimage = new byte[fs.Length];
fs.Read(bimage, 0, Convert.ToInt32(fs.Length));
fs.Close();
SqlCommand cmd = new SqlCommand("insert into tbl_products(Product_image) values(@imgdata)", cn);
cmd.Parameters.AddWithValue("@imgdata", SqlDbType.Image).Value = bimage;
cmd.ExecuteNonQuery();
cn.Close();

It's note clear where you are going to upload your image. If you just want to use an image in a simple desktop application you can use OpenFileDialog to allow a user to select an image file. And then you can use this image path in you application. If you you want to upload this image to database you can read this image into memory using something like FileStream class.

private void cmdBrowser_Click(object sender, EventArgs e)
        {
            OpenFileDialog fileOpen = new OpenFileDialog();
            fileOpen.Title = "Open Image file";
            fileOpen.Filter = "JPG Files (*.jpg)| *.jpg";

            if (fileOpen.ShowDialog() == DialogResult.OK)
            {
                picImage.Image = Image.FromFile(fileOpen.FileName);
            }
            fileOpen.Dispose();
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM