How can I save the path of an image in OpenFileDialog to a string?

1.2k Views Asked by At

I am currently working on a small DB project in which I have tried implementing a browser for image so that they can be saved for each player accordingly.

I am particularly struggling with wring the path of the image to a string, and the storing that string into the arraylist which will then be used to load the file by using the path stored in that arraylist. As you see in the code I have tried to assign the OpenFd.FileName to a string called pathToImage but it doesn't work, the string remains empty after a quick debug check using MessageBox.Show(pathToImage)

Can anyone help me?

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using System.Collections;
using System.Text.RegularExpressions;
using System.Runtime.Serialization.Formatters.Binary;

namespace Assignment1_Template2
{
public partial class Form1 : Form
{

    // =======================The data Structure ===========================
    // ========Uses [SERIALIZABLE] to allow simple loading/saving ==========
    [Serializable]
    private struct myStruct
    {   // The "constructor". Fills data structure with default values
        public myStruct(int playerId)
        {
            uniquePlayerId = new int[playerId];
            playerIgName = "";
            contactStreet = "";
            contactTown = "";
            contactPostcode = "";
            contactEmail = "";
            contactTelephone = "";
            imagePath = "";
            for (int i = 0; i < playerId; ++i) uniquePlayerId[i] = 0;
        }

        // The data types of the struct
        public int[]  uniquePlayerId;
        public string playerIgName;
        public string contactStreet;
        public string contactTown;
        public string contactPostcode;
        public string contactEmail;
        public string contactTelephone;
        public string imagePath;
    }
    // ================== End of data Structure definition ===================
    // =======================================================================


    // ================ Global Variables used in the Program =================
    private ArrayList dataList;         // This is the main data collection
    private int currentEntryShown = 0;    // current myStruct on display
    private int numberOfEntries = 0;    // total number of myStructs
    private string filename = "C:\\test.dat"; // path of the file being read in
    public string pathToImage = "";
    public string pathToImagePlaceholder = "";
    // =======================================================================


    // ================== STARTING POINT FOR THE PROGRAM =====================
    public Form1()
    {

        // Brings up the window.
        InitializeComponent();

        // Create the ArrayList
        dataList = new ArrayList();

        // Call methods implemented below
        LoadData();
        ShowData();
        UpdatePrevNextBtnStatus();
    }
    // =========================================================================
    // =================== END OF STARTING POINT FOR PROGRAM ===================
    // ========= All further events are now triggered by user actions ==========
    // =========================================================================


    // =========================================================================
    // ========================= BUTTON ACTION HANDLERS ========================
    // =========================================================================
    private void showPreviousBtn_Click(object sender, EventArgs e)
    {
        --currentEntryShown;
        ShowData();
        UpdatePrevNextBtnStatus();
    }

    private void showNextBtn_Click(object sender, EventArgs e)
    {
        ++currentEntryShown;
        if (currentEntryShown != dataList.Count)
        {
            ShowData();
        }
        UpdatePrevNextBtnStatus();
    }

    private void addNewPlayerBtn_Click(object sender, EventArgs e)
    {
        ++numberOfEntries; // "Add" clicked: we need to create one more entry
        currentEntryShown = numberOfEntries - 1; // scroll to an empty record at the end

        // Create a new data structure, its constructor will fill it with default values
        myStruct aNewStruct = new myStruct(5);

        dataList.Add(aNewStruct); // add the frshly created struct to the ArrayList


        ShowData();  // display
        addNewPlayerBtn.Enabled = true; // can't do this again before saving
        UpdatePrevNextBtnStatus();
    }
    private void SaveBtn_Click(object sender, EventArgs e)
    {
        SaveData();                 // Call the Save() method implemented below
        addNewPlayerBtn.Enabled = true;      // After saving we can add another new record
        UpdatePrevNextBtnStatus();  // Set 'Next' and 'Previous' button appearance
    }
    // =========================================================================



    // =========================================================================
    // ================ HANDLE DATA CHANGES BY USER ============================
    // =========================================================================
    // If the text box string is changed by the user, update 
   private void playerIdBox_TextChanged(object sender, EventArgs e)
   {
        myStruct aNewStruct = new myStruct(5);
        aNewStruct = (myStruct)dataList[currentEntryShown];
        aNewStruct.uniquePlayerId[0] = Convert.ToInt32(playerIdBox.Text);
        dataList[currentEntryShown] = aNewStruct;
   }
   private void playerIgNameBox_TextChanged(object sender, EventArgs e)
   {
       myStruct aNewStruct = new myStruct(5);
       aNewStruct = (myStruct)dataList[currentEntryShown];
       aNewStruct.playerIgName = playerIgNameBox.Text;
       dataList[currentEntryShown] = aNewStruct;
   }
   private void contactStreetBox_TextChanged(object sender, EventArgs e)
   {
       myStruct aNewStruct = new myStruct(5);
       aNewStruct = (myStruct)dataList[currentEntryShown];
       aNewStruct.contactStreet = contactStreetBox.Text;
       dataList[currentEntryShown] = aNewStruct;
   }

   private void contactTownBox_TextChanged(object sender, EventArgs e)
   {
       myStruct aNewStruct = new myStruct(5);
       aNewStruct = (myStruct)dataList[currentEntryShown];
       aNewStruct.contactTown = contactTownBox.Text;
       dataList[currentEntryShown] = aNewStruct;
   }

   private void contactPostcodeBox_TextChanged(object sender, EventArgs e)
   {
       myStruct aNewStruct = new myStruct(5);
       aNewStruct = (myStruct)dataList[currentEntryShown];
       aNewStruct.contactPostcode = contactPostcodeBox.Text;
       dataList[currentEntryShown] = aNewStruct;
   }

   private void contactEmailBox_TextChanged(object sender, EventArgs e)
   {
       myStruct aNewStruct = new myStruct(5);
       aNewStruct = (myStruct)dataList[currentEntryShown];
       aNewStruct.contactEmail = contactEmailBox.Text;
       dataList[currentEntryShown] = aNewStruct;
   } 

   private void contactTelephoneBox_TextChanged(object sender, EventArgs e)
   {
       myStruct aNewStruct = new myStruct(5);
       aNewStruct = (myStruct)dataList[currentEntryShown];
       aNewStruct.contactTelephone = contactTelephoneBox.Text;
       dataList[currentEntryShown] = aNewStruct;
   }

    // =========================================================================
    // ================= HELPER METHODS FOR DISPLAYING DATA ====================
    // =========================================================================

    private void ShowData()
    {

        playerIdBox.Text = ((myStruct)dataList[currentEntryShown]).uniquePlayerId[0].ToString();
        playerIgNameBox.Text = ((myStruct)dataList[currentEntryShown]).playerIgName;
        contactStreetBox.Text = "" + ((myStruct)dataList[currentEntryShown]).contactStreet;
        contactTownBox.Text = "" + ((myStruct)dataList[currentEntryShown]).contactTown;
        contactPostcodeBox.Text = "" + ((myStruct)dataList[currentEntryShown]).contactPostcode;
        contactEmailBox.Text = "" + ((myStruct)dataList[currentEntryShown]).contactEmail;
        contactTelephoneBox.Text = "" + ((myStruct)dataList[currentEntryShown]).contactTelephone;
        pathToImagePlaceholder = "" + ((myStruct)dataList[currentEntryShown]).imagePath;
        MessageBox.Show(pathToImagePlaceholder);
        try
        {
            playerPictureBox.Image = Image.FromFile(pathToImagePlaceholder);
        }
        catch
        {
            return;
        }


    }

    private void UpdatePrevNextBtnStatus()
    {
        if (currentEntryShown > 0) showPreviousBtn.Enabled = true;
        else showPreviousBtn.Enabled = false;

        if (currentEntryShown < (numberOfEntries - 1)) showNextBtn.Enabled = true;
        else showNextBtn.Enabled = false;

        label1.Text = "Player ID";
        label3.Text = (currentEntryShown + 1) + " / " + numberOfEntries;
    }
    // =========================================================================



    // =========================================================================
    // =============== HELPER METHODS FOR LOADING AND SAVING ===================
    // =========================================================================
    private void SaveData()
    {
        try
        {
            FileStream fs = new FileStream(filename, FileMode.Create, FileAccess.Write);
            try
            {
                BinaryFormatter bf = new BinaryFormatter();
                bf.Serialize(fs, dataList);
                MessageBox.Show("Data saved to " + filename, "FILE SAVE OK", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch
            {
                MessageBox.Show("Could not serialise to " + filename,
                                 "FILE SAVING PROBLEM", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
            fs.Close();
        }
        catch
        {
            MessageBox.Show("Could not open " + filename +
                            " for saving.\nNo access rights to the folder, perhaps?",
                             "FILE SAVING PROBLEM", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
        }
    }
    private void LoadData()
    {

        try
        {
            FileStream fs = new FileStream(filename, FileMode.Open, FileAccess.Read);
            try
            {
                BinaryFormatter bf = new BinaryFormatter();
                dataList = (ArrayList)bf.Deserialize(fs);

                currentEntryShown = 0;
                numberOfEntries = dataList.Count;
            }
            catch
            {
                MessageBox.Show("Could not de-serialise from " + filename +
                                "\nThis usually happens after you changed the data structure.\nDelete the data file and re-start program\n\nClick 'OK' to close the program",
                                "FILE LOADING PROBLEM", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                fs.Close();             // close file
                Environment.Exit(1);    // crash out
            }
            fs.Close();
        }
        catch
        {
            if (MessageBox.Show("Could not open " + filename + " for loading.\nFile might not exist yet.\n(This would be normal at first start)\n\nCreate a default data file?",
                                "FILE LOADING PROBLEM", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation) == DialogResult.Yes)
            {
                // No data exist yet. Create a first entry 
                myStruct aNewStruct = new myStruct(5);
                dataList.Add(aNewStruct);
                numberOfEntries = 1;
                currentEntryShown = 0;
            }
        }

    }
    // =========================================================================


    // =========================================================================
    // ====================== HELPER METHODS FOR SORTING =======================
    // =========================================================================
    // This function will sort by player name by using the PlayerNameComparer below
    private void sortToolStripMenuItem_Click(object sender, EventArgs e)
    {
        dataList.Sort(new PlayerNameComparer());
        currentEntryShown = 0;
        ShowData();
        UpdatePrevNextBtnStatus();
    }
    // Overriding (= overwriting) the default IComparer
    public class PlayerNameComparer : IComparer
    {
        public int Compare(object x, object y)
        {
            return ((myStruct)x).playerIgName.CompareTo(((myStruct)y).playerIgName);
        }
    }

    private void saveButton_Click(object sender, EventArgs e)
    {
        SaveData();
        UpdatePrevNextBtnStatus();

    }

    private void deletePlayerBtn_Click(object sender, EventArgs e)
    {
         dataList.RemoveAt(currentEntryShown);
        SaveData();
        if (currentEntryShown != dataList.Count)
        {
            ShowData();
        }
        UpdatePrevNextBtnStatus();
    }

    private void searchToolStripMenuItem_Click(object sender, EventArgs e)
    {
        Form searchForm = new Form1();
        searchForm.Show();
    }

    private void uploadButton_Click(object sender, EventArgs e)
    {
        try
        {
            OpenFileDialog OpenFd = new OpenFileDialog();
            pathToImage = OpenFd.FileName;
            OpenFd.Filter = "Images only. |*.jpeg; *.jpg; *.png; *.gif;";
            DialogResult rd = OpenFd.ShowDialog();
            if (rd == System.Windows.Forms.DialogResult.OK)
            {
                playerPictureBox.Image = Image.FromFile(OpenFd.FileName);

                myStruct aNewStruct = new myStruct(5);
                aNewStruct = (myStruct)dataList[currentEntryShown];
                aNewStruct.imagePath = pathToImage;
                dataList[currentEntryShown] = aNewStruct;
                // save the FileName to a string.
            }
            MessageBox.Show(pathToImage);

        }
        catch (Exception ex)
        {
            MessageBox.Show("Error: " + ex.Message);
        }
        }

    } 

} 
2

There are 2 best solutions below

0
On BEST ANSWER

I could be wrong because reading all that wall of code requires too much time, but your last method should be

private void uploadButton_Click(object sender, EventArgs e)
{
    try
    {
        OpenFileDialog OpenFd = new OpenFileDialog();
        // REMOVED HERE .... pathToImage = OpenFd.FileName
        OpenFd.Filter = "Images only. |*.jpeg; *.jpg; *.png; *.gif;";
        DialogResult rd = OpenFd.ShowDialog();
        if (rd == System.Windows.Forms.DialogResult.OK)
        {
            playerPictureBox.Image = Image.FromFile(OpenFd.FileName);

            myStruct aNewStruct = new myStruct(5);
            aNewStruct = (myStruct)dataList[currentEntryShown];
            aNewStruct.imagePath = OpenFd.FileName;  // Changed this line...
            dataList[currentEntryShown] = aNewStruct;
        }

        // no much sense this here if the user cancel the dialogbox 
        // MessageBox.Show(pathToImage);

    }
0
On

Set pathToImage after the ShowDIalog has completed, not before:

DialogResult rd = OpenFd.ShowDialog();
if (rd == System.Windows.Forms.DialogResult.OK)
{
    pathToImage = OpenFd.FileName; ...