BillHung.Net


powered by FreeFind     sms

Lab 06 GUI Photo Viewer

12 Dec 2006

Output

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace Lab06_GUI_Photo_Viewer
{
//Bill Chun Wai Hung
//learn loading pictures with DataGridView
//used regex

public partial class Form1 : Form
{
private DataTable photoDataTable = null;
private System.IO.StreamReader reader = null;
private string currentCvsFile = null;
int rowIndex = 0;

//the entry point of the program
public Form1()
{
InitializeComponent();

CreateTable();
currentCvsFile = "photo.csv";
ReadPhotoCVS(currentCvsFile);
}

//prepare the columns of the DataTable within the DataGrid
private void CreateTable()
{
photoDataTable = new DataTable("photoDataTable");
photoDataTable.Columns.Add("Photo");
photoDataTable.Columns.Add("Description");
dataGridView1.DataSource = photoDataTable;

}

//reading the data from a cvs file
public void ReadPhotoCVS(string currentCvsFile)
{
System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex(@",");
string[] photoData;

try
{ reader = new System.IO.StreamReader(currentCvsFile); }
catch
{ Console.WriteLine("open file {0} error\n", currentCvsFile); }

for (string line = reader.ReadLine(); line != null; line = reader.ReadLine())
{
Console.WriteLine(line);

photoData = regex.Split(line);
photoDataTable.Rows.Add(photoData);
}
reader.Close();
dataGridView1.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCells);
}

//when the selection of DataGridViewChanged
private void dataGridView1_SelectionChanged(object sender, EventArgs e)
{
try
{
rowIndex = dataGridView1.CurrentRow.Index;
textBox1.Text = dataGridView1.CurrentRow.Cells["Description"].FormattedValue.ToString();
String dataGridFileName = dataGridView1.CurrentRow.Cells["Photo"].FormattedValue.ToString();
Image image = Image.FromFile(dataGridFileName);
pictureBox1.Image = image;
}
catch { }
}

//clicking the << button decrement the index of the pictures
private void button1_Click(object sender, EventArgs e)
{
string strTemp = null;
rowIndex = dataGridView1.CurrentRow.Index;
if (rowIndex > 0)
{
strTemp = dataGridView1.Rows[rowIndex - 1].Cells[0].Value.ToString();
Image image = Image.FromFile(strTemp);
pictureBox1.Image = image;
}
}

//clicking the >> button increment the index of the pictures
private void button2_Click(object sender, EventArgs e)
{
string strTemp = null;
rowIndex = dataGridView1.CurrentRow.Index;
if (rowIndex < (dataGridView1.Rows.Count-2))
{
strTemp = dataGridView1.Rows[rowIndex + 1].Cells[0].Value.ToString();
Image image = Image.FromFile(strTemp);
pictureBox1.Image = image;
} 
}
}
}