【问题标题】:devExpress GridView EditForm does not allow image fields to be updateddevExpress GridView EditForm 不允许更新图像字段
【发布时间】:2016-06-29 07:38:43
【问题描述】:

我有一个带有图像列的 GridView。当我单击每列 EditForm 打开并编辑我的数据然后按更新按钮并将数据存储回 GridView 时。但是当我添加图像列并尝试使用 EditForm 保存图像时,出现以下错误,无法单击更新按钮。

当我使用 InPlace 编辑模式时没有问题。就在我使用 EditForm 时,会出现此问题:

【问题讨论】:

    标签: c# gridview devexpress devexpress-windows-ui


    【解决方案1】:

    这是因为如果您使用 byte[] 类型来表示您的图像数据。 GridControl 本身可以正确地直接操作字节,并正确地将位图转换为图像字节并返回。这就是 Inplace 编辑模式没有问题的原因。

    在 EditForm 模式下工作时,标准的 WinForms 绑定用于将图像数据传递到 EditForm 的编辑器并返回。并且标准绑定无法将您加载到 PictureEdit 中的位图转换回图像字节数组。这就是您看到验证错误的原因。

    要解决这个问题,您应该避免类型转换,通过使用确切的Image 类型来表示图像数据或修补标准绑定,如下所示:

    public class Person {
        public byte[] Photo { get; set; }
    }
    //...
    gridView1.OptionsBehavior.EditingMode = DevExpress.XtraGrid.Views.Grid.GridEditingMode.EditForm;
    gridView1.EditFormPrepared += gridView1_EditFormPrepared;
    gridControl1.DataSource = new List<Person> { 
        new Person()
    };
    //...
    void gridView1_EditFormPrepared(object sender, DevExpress.XtraGrid.Views.Grid.EditFormPreparedEventArgs e) {
        var binding = e.BindableControls["Photo"].DataBindings["EditValue"];
        binding.Parse += binding_ParseImageIntoByteArray;
    }
    void binding_ParseImageIntoByteArray(object sender, ConvertEventArgs e) {
        Image img = e.Value as Image;
        if(img != null && e.DesiredType == typeof(byte[])) {
            using(var ms = new System.IO.MemoryStream()) {
                img.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
                // get bytes
                e.Value = ms.GetBuffer();
            }
        }
    }
    

    【讨论】:

    • 非常清楚。谢谢。但我正在使用实体框架来填充网格视图。我现在应该将我的列类型图像更改为数据库中的字节吗?还是我应该只编辑我的实体框架说 Person 类?有没有更简单的方法?
    • 图像在数据库中存储为字节?
    • 还有第三种可能的解决方案:您可以编写一个未映射到 DB 字段的包装器属性(我建议使用部分类方法)并使用此属性进行绑定。在这个包装器中,您可以执行转换。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-02-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多