0

I have a GridView with image column. when I click on each column EditForm opens and I edit my data then press Update button and data is stored back to GridView. but when I add an image column and try to save an image using EditForm I get the following error preventing clicking Update button.

When I use InPlace editing mode there is no problem. just when I use EditForm this issue occurs:

My Error

Ali.Rashidi
  • 1,284
  • 4
  • 22
  • 51

1 Answers1

1

This happens because if you are using the byte[] type to represent your image data. The GridControl itself can correctly operate with bytes directly and correctly convert Bitmap into image-bytes and back. That's why there is no problem in Inplace edit mode.

When working in EditForm mode, the standard WinForms binding is used to pass image-data into EditForm's editor and back. And the standard binding can't convert the Bitmap which you're loaded into the PictureEdit back to image-bytes array. That's why you see the validation error.

To overcome this issue you should either avoid types conversion via using the exact Image type to represent image-data or patch the standard binding as follows:

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();
        }
    }
}
DmitryG
  • 17,677
  • 1
  • 30
  • 53
  • very clear. thanks. but I'm using entity framework to populate grid-view. should I change my column type of image to byte in database now? or should I just edit my Entity Framework say Person class? is there a simpler way? – Ali.Rashidi Jun 29 '16 at 14:01
  • images are stored as byte in DB? – Ali.Rashidi Jun 29 '16 at 14:02
  • There is a third possible solution for you: you can write a wrapper-property(I suggest to use the partial-class approach) which is not mapped to DB field and use this property for binding. Within this wrapper you can perform the conversion. – DmitryG Jun 29 '16 at 15:13