Search code examples
c#winformsdata-binding

Databinding PictureBox to relative path in winform


I have a winform that pull data from database into a DataGridView and Databind it to several text box and a PictureBox. I have a databinding and data loading method to reload and rebind when there is change in the data as below.

private void LoadData()
        {
            DataTable dtDS = new System.Data.DataTable();
            dtDS = prodController.GetData();
            dgvProduct.DataSource = dtDS;
        }
private void DataBinding()
        {
            txtProductID.DataBindings.Clear();
            txtProductID.DataBindings.Add("Text", dgvProduct.DataSource, "ProductID");
            txtProductName.DataBindings.Clear();
            txtProductName.DataBindings.Add("Text", dgvProduct.DataSource, "ProductName");
            ...
            bxImage.DataBindings.Clear();
            bxImage.DataBindings.Add("ImageLocation", dgvProduct.DataSource, "ImagePath");
        }

At first I stored the absoluted path of the image in the database as string and it worked fine binding the data into the control. But after that I want to only store the image name in the database, the image themselves are moved to an Image folder in the Application startup folder so that I can load the Image like this:

bxImage.Image = Image.FromFile(Application.StartupPath + @"\Image\Student\" + imagePath);

I followed Databinding a label in C# with additional text? to add like below to my DataBinding method:

var binding = new Binding("ImageLocation", dgvProduct.DataSource, "ImagePath");
            binding.Format += delegate (object sentFrom, ConvertEventArgs convertEventArgs)
            {
                convertEventArgs.Value = Application.StartupPath + @"\Image\" + convertEventArgs.Value;
            };
            bxImage.DataBindings.Add(binding);

It worked as first but after each time the LoadData and DataBinding are called the string keep adding onto each other making the path invalid. Even if I called the DataBinding clear and reset the format it still adding each time the methods is called. Is there a way to properly do this or should I use CellClicked method of DataGridView to get the image to load into the PictureBox?


Solution

  • I know this is long overdue but I should update the answer for anyone who stumble upon this problem the same as me. Thanks @TaW for the answer. In the binding.Format change the code to this:

    String path = convertEventArgs.Value.ToString();
    if (!path.StartsWith(Application.StartupPath + @"\Image\"))
    {
        convertEventArgs.Value = Application.StartupPath + @"\Image\" + convertEventArgs.Value;
    }
    

    This should prevent the string to be added each time the DataBinding is called and help bind the data to the control properly.