【问题标题】:Databinding PictureBox to relative path in winform将图片框数据绑定到winform中的相对路径
【发布时间】:2019-05-02 08:17:30
【问题描述】:

我有一个将数据从数据库中提取到 DataGridView 并将其数据绑定到多个文本框和一个 PictureBox 的 winform。我有一个数据绑定和数据加载方法,可以在数据发生变化时重新加载和重新绑定,如下所示。

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");
        }

起初,我将图像的绝对路径作为字符串存储在数据库中,它可以很好地将数据绑定到控件中。但之后我只想将图像名称存储在数据库中,图像本身被移动到应用程序启动文件夹中的图像文件夹,以便我可以像这样加载图像:

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

我按照Databinding a label in C# with additional text? 将如下内容添加到我的 DataBinding 方法中:

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);

它像第一次一样工作,但每次调用 LoadData 和 DataBinding 后,字符串不断相互添加,使路径无效。即使我清除了 DataBinding 并重置了格式,它仍然在每次调用方法时添加。有没有办法正确执行此操作,或者我应该使用 DataGridView 的 CellClicked 方法将图像加载到 PictureBox 中?

【问题讨论】:

  • 那么,如果您在 delgate 中设置断点并查看convertEventArgs.Value 它会堆积路径数据??诡异的!您能否测试 StartsWith 作为解决方法?
  • 这可能看起来很愚蠢,但我应该把 StartsWith 放在哪里?
  • 在修改值之前,可能像if (!convertEventArgs.Value.StartsWith(Application.StartupPath)).. - 但这只是一种解决方法。最好找到多次添加的原因..!
  • 我不知道这是否可行,因为例如,应用程序存储在 C 盘中的文件夹 Project 中,第一次调用 Binding 方法时,值将是这样的:C:\ \Project\\Image\\Picture.png,但第二次变成这样:C:\\Project\\Image\\C:\\Project\\Image\\Picture.png。由于它们都以相同的方式开始,因此仍然会产生相同的结果
  • 好吧,我不知道这是否是个好主意,但我写了一个 negated 条件 (!)。真正的问题是(除了找到原始原因之外)图像名称本身是否正确..

标签: c# winforms data-binding


【解决方案1】:

我知道这早就应该更新了,但我应该为那些和我一样偶然发现这个问题的人更新答案。感谢@TaW 的回答。在binding.Format 中将代码更改为:

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

这应该可以防止每次调用 DataBinding 时添加字符串,并有助于将数据正确绑定到控件。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-06-05
    • 1970-01-01
    • 2016-01-09
    • 1970-01-01
    • 1970-01-01
    • 2014-10-15
    • 1970-01-01
    相关资源
    最近更新 更多