NEWS

[DEVEXPRESS] Hướng dẫn cách hiển thị hình ảnh Glyph trên SearchLookupEdit

[DEVEXPRESS] Hướng dẫn cách hiển thị hình ảnh Glyph trên SearchLookupEdit
Đăng bởi: Thảo Meo - Lượt xem: 4137 15:20:22, 07/07/2021DEVEXPRESS   In bài viết

Xin chào các bạn, bài viết hôm nay mình sẽ tiếp tục hướng dẫn các bạn cách hiển thị hình ảnh kế bên SearchLookupEdit, sau khi chúng ta chọn dữ liệu trên Devexpress C#.

[C#] Display Search Lookup Edit with Glyph 

Dưới đây là hình ảnh demo:

image_search_lookup_edit

Ở hình trên các bạn thấy, sau khi mình chọn thông tin xong thì có hình ảnh hiển thị kế bên SearchLookupEdit.

Để làm được vậy, các bạn cần phải customize control SearchLookupEdit lại.

Video demo ứng dụng:

Đầu tiên, các bạn tạo cho mình class với tên: RepositoryItemSearchLookUpEditWithGlyph.cs

Source code C# Search Lookup Edit with Image:

using System;
using System.Text;
using DevExpress.XtraEditors;
using DevExpress.XtraEditors.Repository;
using DevExpress.XtraEditors.ViewInfo;
using DevExpress.XtraEditors.Drawing;
using System.Drawing;
using System.ComponentModel;
using DevExpress.XtraEditors.Registrator;
using DevExpress.XtraEditors.Controls;

namespace ImageSearchLookupEdit {
    public class RepositoryItemSearchLookUpEditWithGlyph : RepositoryItemSearchLookUpEdit {
        static RepositoryItemSearchLookUpEditWithGlyph() {
            RegisterSearchLookUpEditWithGlyph();
        }
        protected ImageByValueEventHandler getImageByValueEventHandler = null;
        public event ImageByValueEventHandler GetImageByValue {
            add { getImageByValueEventHandler += value; }
            remove { getImageByValueEventHandler -= value; }
        }
        public object GetImage(ImageByValueEventArgs e) {
            RaiseGetImageByValue(e);
            return e.Image;
        }
        protected void RaiseGetImageByValue(ImageByValueEventArgs e) {
            if(getImageByValueEventHandler != null)
                getImageByValueEventHandler(this, e);
        }
        public override string EditorTypeName { get { return "SearchLookUpEditWithGlyph"; } }
        public static void RegisterSearchLookUpEditWithGlyph() {
            EditorRegistrationInfo.Default.Editors.Add(new EditorClassInfo("SearchLookUpEditWithGlyph", typeof(SearchLookUpEditWithGlyph), typeof(RepositoryItemSearchLookUpEditWithGlyph),
                typeof(SearchLookUpEditWithGlyphBaseViewInfo), new SearchEditPainterWithGlyph(), false));
        }
        public override void Assign(RepositoryItem item) {
            RepositoryItemSearchLookUpEditWithGlyph li = item as RepositoryItemSearchLookUpEditWithGlyph;
            if(li != null) {
                this.GetImageByValue += li.getImageByValueEventHandler;
            }
            base.Assign(item);
        }
        protected override void ClearClick() {
            base.ClearClick();
            SearchLookUpEditWithGlyph edit = OwnerEdit as SearchLookUpEditWithGlyph;
            if(edit != null) {
                edit.Image = null;
                edit.DoValidate();
            }
        }
    }
    public class SearchEditPainterWithGlyph : ButtonEditPainter {
        protected override void DrawGlyphCore(ControlGraphicsInfoArgs info, ButtonEditViewInfo be) {
            SearchLookUpEditWithGlyphBaseViewInfo vi = be as SearchLookUpEditWithGlyphBaseViewInfo;
            if(vi.Image == null) return;
            if(vi.Image.Size.Width > SearchLookUpEditWithGlyphBaseViewInfo.DefaultImageSize.Width * 2)
                info.Graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
            info.Paint.DrawImage(info.Graphics, vi.Image, vi.GlyphBounds, new Rectangle(Point.Empty, vi.Image.Size), vi.State != DevExpress.Utils.Drawing.ObjectState.Disabled);
        }
    }
    public class SearchLookUpEditWithGlyphBaseViewInfo : SearchLookUpEditBaseViewInfo {
        Image imageCore;
        public static Size DefaultImageSize = new Size(17, 17);
        public SearchLookUpEditWithGlyphBaseViewInfo(RepositoryItem item) : base(item) { }
        public new SearchLookUpEditWithGlyph OwnerEdit { get { return base.OwnerEdit as SearchLookUpEditWithGlyph; } }
        public new RepositoryItemSearchLookUpEditWithGlyph Item { get { return base.Item as RepositoryItemSearchLookUpEditWithGlyph; } }
        public override bool IsExistImage { get { return true; } }
        public override Size ImageSize { get { return Image == null ? Size.Empty : DefaultImageSize; } }
        public override DevExpress.Utils.Drawing.TextGlyphDrawModeEnum GlyphDrawMode {
            get {
                if(ImageSize.IsEmpty) return DevExpress.Utils.Drawing.TextGlyphDrawModeEnum.Text;
                return DevExpress.Utils.Drawing.TextGlyphDrawModeEnum.TextGlyph;
            }
        }
        bool requireUpdateImage = false;
        protected override void OnEditValueChanged() {
            base.OnEditValueChanged();
            if(Bounds.IsEmpty) {
                this.requireUpdateImage = true;
                return;
            }
            UpdateImage();
        }
        public override void CalcViewInfo(Graphics g) {
            if(requireUpdateImage || OwnerEdit != null && OwnerEdit.Image != null) UpdateImage();
            base.CalcViewInfo(g);
        }
        public override void Reset() {
            base.Reset();
            this.imageCore = null;
        }

        void UpdateImage() {
            this.requireUpdateImage = false;
            this.imageCore = GetImageCore(EditValue);
        }
        Image GetImageCore(object editValue) {
            object ret = null;
            if(OwnerEdit != null) ret = OwnerEdit.Image;
            if(ret != null) return (Image)ret;

            if(Item != null && editValue != nullValue)
                ret = Item.GetImage(new ImageByValueEventArgs(editValue));
            if(ret == null) return null;
            if(ret is Image) return (Image)ret;
            return ByteImageConverter.FromByteArray(ByteImageConverter.ToByteArray(ret));
        }
        public Image Image {
            get {
                return imageCore;
            }
        }
    }
    public class SearchLookUpEditWithGlyph : SearchLookUpEdit {
        Image imageCore;
        static SearchLookUpEditWithGlyph() {
            RepositoryItemSearchLookUpEditWithGlyph.RegisterSearchLookUpEditWithGlyph();
        }
        public override string EditorTypeName { get { return "SearchLookUpEditWithGlyph"; } }
        protected override void Dispose(bool disposing) {
            if(disposing && imageCore != null) imageCore.Dispose();
            this.imageCore = null;
            base.Dispose(disposing);
        }
        [DefaultValue(null)]
        public Image Image {
            get { return imageCore; }
            set {
                imageCore = value;
                LayoutChanged();
            }
        }
    }
    public delegate void ImageByValueEventHandler(object sender, ImageByValueEventArgs e);
    public class ImageByValueEventArgs : EventArgs {
        object valueCore;
        object imageCore;
        public ImageByValueEventArgs(object value) {
            this.valueCore = value;
        }
        public object Value { get { return valueCore; } }
        public object Image { 
            get { return imageCore; } 
            set { imageCore = value; } 
        }
    }
}

Sau đó, các bạn Build project và từ thanh Toolbox, các bạn kéo control mới custom này vào sử dụng.

Full source code FrmMain hiển thị hình ảnh:

using DevExpress.XtraGrid.Views.Grid;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ImageSearchLookupEdit
{
    public partial class Form1 : DevExpress.XtraEditors.XtraForm
    {
        public Form1()
        {
            InitializeComponent();
            searchEdit.Properties.ShowClearButton = false;
            searchLookUpEditWithGlyph1View.CustomUnboundColumnData += SearchLookUpEditWithGlyph1View_CustomUnboundColumnData;
            searchEdit.EditValueChanged += SearchLookUpEditWithGlyph1_EditValueChanged;
        }

        private void SearchLookUpEditWithGlyph1_EditValueChanged(object sender, EventArgs e)
        {
            SearchLookUpEditWithGlyph edit = sender as SearchLookUpEditWithGlyph;
            if (edit == null) return;
            if (edit.EditValue == null)
                edit.Image = null;
            else
            {
                DataTable dt = edit.Properties.DataSource as DataTable;
                if (dt == null)
                    return;
               
                edit.Image = dic_image.Where(b => b.Key == edit.EditValue.ToString()).FirstOrDefault().Value;
               var rowSelected = dt.AsEnumerable().Where(x => x["id"].ToString() == edit.EditValue.ToString()).FirstOrDefault();
                lbl_name.Text = rowSelected["name"].ToString();
                lbl_address.Text = rowSelected["address"].ToString();                
            }
            pic_employee.Image = edit.Image;
        }

        Dictionary<string, Image> dic_image = new Dictionary<string, Image>();
        private void SearchLookUpEditWithGlyph1View_CustomUnboundColumnData(object sender, DevExpress.XtraGrid.Views.Base.CustomColumnDataEventArgs e)
        {
            if(e.Column.Caption == "Image Employee")
            {               
                var datarow = (e.Row as DataRowView).Row as DataRow;
                var id = datarow["id"].ToString();
              
                if (!dic_image.ContainsKey(id))
                {
                    Task.Run(() =>
                    {
                        var pic = new PictureBox();
                        var url_image = datarow["url_image"].ToString();
                        pic.Load(url_image);
                        var pic_thumb = pic.Image.GetThumbnailImage(80, 100, null, IntPtr.Zero);
                        if (!dic_image.ContainsKey(id))
                        {
                            dic_image.Add(id, pic_thumb);
                        }
                        e.Value = pic_thumb;
                        searchLookUpEditWithGlyph1View.RefreshData();
                    });
                }
                else
                {
                    e.Value = dic_image.Where(b => b.Key == id).FirstOrDefault().Value;
                }
            }
        }

        public DataTable InitEmployee()
        {
            var table = new DataTable();
            table.Columns.Add("id", typeof(int));
            table.Columns.Add("name", typeof(string));
            table.Columns.Add("address", typeof(string));
            table.Columns.Add("url_image", typeof(string));

            table.Rows.Add(1, "Nguyễn Thảo", "Vũng Tàu", "https://laptrinhvb.net/uploads/users/f536577444a10a5121052df0842c542c.png");
            table.Rows.Add(2, "Nguyễn Đình Tuyên", "Quảng Bình", "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTGoUz_1tD1I_8eGcnYYIcZpP2NYKfVlARdxw&usqp=CAU");
            table.Rows.Add(3, "Trịnh Quốc Khang", "Đồng Nai", "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQyS_Kl32X4ufwhUuGv1K_jx52PvhFWh7-epw&usqp=CAU");
            table.Rows.Add(4, "Cái Trí Minh", "Quảng Trị", "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTt9GID60Kc-Qc0m58FSMTZSy_UR6GRi6SfQw&usqp=CAU");
            table.Rows.Add(5, "Võ Sơn Băng", "Vĩnh Long", "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTGoUz_1tD1I_8eGcnYYIcZpP2NYKfVlARdxw&usqp=CAU");
            table.Rows.Add(6, "Nguyễn Thị Cẩm Tú", "Kiên Giang", "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQkD23KKbwxODc4qTo_zTT0Z3FGl-0uqYQn6w&usqp=CAU");
            table.Rows.Add(7, "Nguyễn Phương Nhi", "TP. Hồ Chí Minh", "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSI41jOxY1v2fkmU95RRCSWPzvOPH_VdnaGrg&usqp=CAU");
            table.Rows.Add(8, "Hoàng Thị Thảo", "Quảng Bình", "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQSs8dfIu2jGXYSwS5f_5KYDRw0bgE61kSzeQ&usqp=CAU");
            return table;
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            searchEdit.Properties.DataSource = InitEmployee();
            searchEdit.Properties.ValueMember = "id";
            searchEdit.Properties.DisplayMember = "name";
            repositoryItemPictureEdit1.SizeMode = DevExpress.XtraEditors.Controls.PictureSizeMode.Zoom;
        }
    }
}

Thanks for watching!

DOWNLOAD SOURCE

THÔNG TIN TÁC GIẢ

BÀI VIẾT LIÊN QUAN

[DEVEXPRESS] Hướng dẫn cách hiển thị hình ảnh Glyph trên SearchLookupEdit
Đăng bởi: Thảo Meo - Lượt xem: 4137 15:20:22, 07/07/2021DEVEXPRESS   In bài viết

CÁC BÀI CÙNG CHỦ ĐỀ

Đọc tiếp
.

Verified Website

See Report