C# Photo Viewer with Windows Forms

A I said,in this article we will create a picture viewer in C#.Let's start by creating a new Windows Forms Aplication Project and add a button,an openfile dialog and a picturebox to our form.



Now,it should look like this,but you can design it however you want.

The first part is finished,so let's start writing the code.

In my case

opnbutton = openbutton
pictureBox1 = the picturebox
openFileDialog1 = the openfile dialog

This is the code

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.ComponentModel;  
  4. using System.Data;  
  5. using System.Drawing;  
  6. using System.Linq;  
  7. using System.Text;  
  8. using System.Windows.Forms;  
  9. using System.IO;  
  10. namespace BeHe_Picture_Viewer   
  11. {  
  12.     public partial class Form1: Form   
  13.     {  
  14.         public string path;  
  15.         public Form1()   
  16.         {  
  17.             InitializeComponent();  
  18.         }  
  19.         private void opnbutton_Click(object sender, EventArgs e)  
  20.         {  
  21.             openFileDialog1.ShowDialog(); //Shows the dialog  
  22.             if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)   
  23.             {  
  24.                 try   
  25.                 {  
  26.   
  27.                     pictureBox1.Load(openFileDialog1.FileName); //Loads the selected file   
  28.                 }  
  29.                 catch   
  30.                 {  
  31.                     MessageBox.Show("Error opening file"); //Sets the erorr  
  32.                 }  
  33.                 path = Path.GetDirectoryName(openFileDialog1.FileName); //Gets the current path  
  34.                 this.Text = "BeHe Picture Viewer - " + path;  
  35.             }  
  36.         }  
  37.     }  
  38. }  
Remember,this is for beginners.I created something similar that can open pictures from the same folder(next and prev button),using System.IO,but this could be a liitle hard at the beginning.

Thanks you guys.

Enjoy.