NEWS

[DEVEXPRESS] Thừa kế control SearchLookupEdit thành MultiSelectGridLookupEdit

[DEVEXPRESS] Thừa kế control SearchLookupEdit thành MultiSelectGridLookupEdit
Đăng bởi: Thảo Meo - Lượt xem: 8454 19:51:17, 08/10/2020C#   In bài viết

Xin chào các bạn, bài viết hôm trước mình đã có hướng dẫn các bạn cách chọn nhiều dòng dữ liệu trên GridLookupEdit, trong bài này mình sẽ tạo control mới thừa kế từ control SearchLookupEdit thành MultiSelectGridLookupEdit.

[DEVEXPRESS] Custom Control SearchLookupEdit to MultiSelectSearchLookupEdit

Trong các công cụ mặc định của Devexpress, nếu các bạn muốn chọn nhiều dòng dữ liệu, các bạn sẽ sử dụng control  CheckedComboboxEdit.

Tuy nhiên khi bạn sử dụng công cụ này, thì các bạn không thể hiển thị nhiều cột dữ liệu, không thể filter lọc và tìm kiếm.

Nên bài viết này, mình xây dựng sẵn công cụ để sử dụng cho công việc hay chọn nhiều dòng dữ liệu một cách dễ dàng và nhanh chóng.

multiselectsearchlookupedit

Ở công cụ này, các bạn muốn lấy dữ liệu sẽ sử dụng Event MultiValueChanged và giá trị trả về là VALUE thay vì EditValue như GridLookupEdit.

Ngoài các bạn, có thể chỉnh sửa thuộc tính icon cho checkbox chọn nhiều dòng ở properties: MulticheckboxStyle, ở ví dụ trên mình sử dụng hình trái tim.

mult_check

Và tiếp theo, là khi các bạn chọn nhiều dữ liệu, displaytext sẽ không hiển thị hết các items các bạn đã chọn.

Các bạn có thể chỉnh sửa 2 thuộc tính sau để nó trả về hiển thị là bao nhiêu items vừa được chọn qua 2 thuộc tính: 

ShowItemCountMulti = trueTextItemsOutofLabel {0} là số dòng chọn nó hiển thị.

multiselectcsharp

Source code custom control MultiSearchLookupEdit Devexpress c#:

using DevExpress.Data;
using DevExpress.Data.Filtering.Helpers;
using DevExpress.Images;
using DevExpress.Utils;
using DevExpress.Utils.Animation;
using DevExpress.Utils.Extensions;
using DevExpress.Utils.Win;
using DevExpress.XtraEditors;
using DevExpress.XtraEditors.Controls;
using DevExpress.XtraEditors.Drawing;
using DevExpress.XtraEditors.Registrator;
using DevExpress.XtraEditors.Repository;
using DevExpress.XtraEditors.ViewInfo;
using DevExpress.XtraGrid.Columns;
using DevExpress.XtraGrid.Localization;
using DevExpress.XtraGrid.Views.Grid;
using DevExpress.XtraLayout;
using DevExpress.XtraPrinting.Export.Pdf;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlTypes;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace multiselectcontrol
{
    [UserRepositoryItem("RegisterMyGridLookUpEdit")]
    public class RepositoryItemMyGridLookUpEdit : RepositoryItemSearchLookUpEdit
    {
        private RepositoryItemCheckEdit repositoryItemCheckEdit;
        public CheckBoxStyle MulticheckBoxStyle { set; get; } = CheckBoxStyle.Default;
        static RepositoryItemMyGridLookUpEdit() { RegisterMyGridLookUpEdit(); }
        public RepositoryItemMyGridLookUpEdit()
        {
        }

        protected override void OnLoaded()
        {
            base.OnLoaded();
            if (IsDesignMode) return;
            GridView gView = this.View;
            gView.OptionsSelection.MultiSelect = true;
            gView.OptionsSelection.MultiSelectMode = GridMultiSelectMode.CheckBoxRowSelect;
            gView.OptionsSelection.CheckBoxSelectorColumnWidth = 40;
            gView.OptionsView.ShowAutoFilterRow = true;
            gView.OptionsBehavior.Editable = false;
            gView.SelectionChanged += GView_SelectionChanged;
            gView.RowCellClick += GView_RowCellClick;
            if (MulticheckBoxStyle != CheckBoxStyle.Default)
            {
                repositoryItemCheckEdit = new RepositoryItemCheckEdit();
                repositoryItemCheckEdit.CheckBoxOptions.Style = MulticheckBoxStyle;
                gView.CustomDrawColumnHeader += GView_CustomDrawColumnHeader;
            }

        }
      
        public void GView_CustomDrawColumnHeader(object sender, ColumnHeaderCustomDrawEventArgs e)
        {
            if (e.Column?.FieldName == "DX$CheckboxSelectorColumn")
            {
                e.Column.ColumnEdit = repositoryItemCheckEdit;
            }
        }

        private void GView_RowCellClick(object sender, RowCellClickEventArgs e)
        {
            GridView view = sender as GridView;
            int i = view.FocusedRowHandle;
            if (view.Columns.Contains(view.FocusedColumn))
            {
                if (view.IsRowSelected(i))
                {
                    view.UnselectRow(i);
                }
                else
                {
                    view.SelectRow(i);
                }
            }
        }

        private void GView_SelectionChanged(object sender, DevExpress.Data.SelectionChangedEventArgs e)
        {
            GridView view = sender as GridView;
            if (view != null)
                view.GetSelectedRows();
        }

        public const string MyGridLookUpEditName = "MultiSelectSearchGridLookUpEdit";
        public override string EditorTypeName { get { return MyGridLookUpEditName; } }
        public static void RegisterMyGridLookUpEdit()
        {
            Image img = null;

            EditorRegistrationInfo.Default.Editors.Add(new EditorClassInfo(MyGridLookUpEditName,
              typeof(MultiSelectLookUpEdit), typeof(RepositoryItemMyGridLookUpEdit),
              typeof(GridLookUpEditBaseViewInfo), new ButtonEditPainter(), true, img));
        }




        public override void Assign(RepositoryItem item)
        {
            BeginUpdate();
            try
            {
                base.Assign(item);
                RepositoryItemMyGridLookUpEdit source =
                    item as RepositoryItemMyGridLookUpEdit;
                if (source == null) return;
            }
            finally
            {
                EndUpdate();
            }
        }

        private void InitializeComponent()
        {
            ((System.ComponentModel.ISupportInitialize)(this)).BeginInit();
            ((System.ComponentModel.ISupportInitialize)(this)).EndInit();

        }

        private IContainer components;
    }

    public class MultiSelectLookUpEdit : SearchLookUpEdit
    {
        public int[] _selectedRows;
        public bool ShowItemCountMulti { set; get; } = false;
        public string TextItemsOutofLabel { set; get; } = "Bạn đã chọn {0}.";
        public string VALUE = "";
        public int[] selectedRows
        {
            set
            {
                this._selectedRows = value;
                if (last_selectedRows == null && _selectedRows == null) { return; }
                if (last_selectedRows == null && _selectedRows != null)
                {
                    this.OnMultiValueChanged(null);
                    return;
                }

                var isDifference = selectedRows.Except(last_selectedRows).Count() != 0;
                if (isDifference)
                {
                    this.OnMultiValueChanged(null);
                    return;
                }

                if (last_selectedRows.Count() != _selectedRows.Count())
                {
                    this.OnMultiValueChanged(null);
                }
            }
            get
            {
                return this._selectedRows;
            }
        }
        public int[] last_selectedRows = null;

        [Category("Action")]
        [Description("Trigger iá trị dữ liệu thay đổi")]
        public event EventHandler MultiValueChanged;

        protected virtual void OnMultiValueChanged(EventArgs e)
        {
            if (MultiValueChanged != null)
                MultiValueChanged(this, e);
        }

        static MultiSelectLookUpEdit()
        {
            RepositoryItemMyGridLookUpEdit.RegisterMyGridLookUpEdit();
        }
        public SvgImageCollection svgImageCollection1;
        public MultiSelectLookUpEdit()
        {

            this.CloseUp += MultiSelectLookUpEdit_CloseUp;
            this.EditValueChanged += MultiSelectLookUpEdit_EditValueChanged;
            this.QueryCloseUp += MultiSelectLookUpEdit_QueryCloseUp;
            this.Popup += MultiSelectLookUpEdit_Popup;
            this.Properties.NullText = "";
            svgImageCollection1 = new SvgImageCollection();

            this.svgImageCollection1.Add("actions_checkcircled", "image://svgimages/icon builder/actions_checkcircled.svg");
            this.svgImageCollection1.Add("actions_zoom", "image://svgimages/icon builder/actions_zoom.svg");

        }

        private void MultiSelectLookUpEdit_Popup(object sender, EventArgs e)
        {
            IPopupControl popupControl = sender as IPopupControl;
            LayoutControl layoutControl = popupControl.PopupWindow.Controls[3].Controls[0] as LayoutControl;
            SimpleButton clearButton = ((LayoutControlItem)layoutControl.Items.FindByName("lciClear")).Control as SimpleButton;
            SimpleButton find = ((LayoutControlItem)layoutControl.Items.FindByName("lciButtonFind")).Control as SimpleButton;
            clearButton.Text = "Đồng ý";
            find.Text = "Tìm kiếm";
            clearButton.ImageOptions.SvgImage = svgImageCollection1[0];
            clearButton.ImageOptions.SvgImageSize = new Size(16, 16);
            find.ImageOptions.SvgImage = svgImageCollection1[1];
            find.ImageOptions.SvgImageSize = new Size(16, 16);
            if (clearButton != null)
            {
                clearButton.Click += ClearButton_Click;
            }
        }
        bool Allowclose = false;

        private void ClearButton_Click(object sender, EventArgs e)
        {
            if (this.IsPopupOpen)
            {
                Allowclose = true;
                this.ClosePopup();
            }
        }

        private void MultiSelectLookUpEdit_QueryCloseUp(object sender, CancelEventArgs e)
        {
            if (!Allowclose)
            {
                e.Cancel = true;
            }

        }

        private void MultiSelectLookUpEdit_EditValueChanged(object sender, EventArgs e)
        {
            this.EditValue = null;
        }

        private void MultiSelectLookUpEdit_CloseUp(object sender, DevExpress.XtraEditors.Controls.CloseUpEventArgs e)
        {
            var repositoryItemMyGridLookUpEdit = this.Properties.View;
            var selected_row = (((DevExpress.XtraEditors.GridLookUpEditBase)(sender)).Properties).View.GetSelectedRows();
            var editValue = string.Join(", ", selected_row.Select(x => repositoryItemMyGridLookUpEdit.GetDataRow(x)[this.Properties.ValueMember].ToString()));
            this.VALUE = editValue;
            selectedRows = selected_row;

            var displayText = string.Join(", ", selectedRows.Select(x => repositoryItemMyGridLookUpEdit.GetDataRow(x)[this.Properties.DisplayMember].ToString()));
            this.Properties.NullText = displayText;

            var width_text = TextRenderer.MeasureText(this.Text, new Font(this.Font.FontFamily, this.Font.Size, this.Font.Style)).Width + 20;
            var width_lookupedit = this.Width;
            if (width_text > width_lookupedit && ShowItemCountMulti)
            {
                if (string.IsNullOrEmpty(TextItemsOutofLabel))
                {
                    TextItemsOutofLabel = "({0}) items.";
                }
                var itemSelected = editValue.Split(',').Length;
                this.Properties.NullText = string.Format(this.TextItemsOutofLabel, itemSelected);
            }
            this.EditValue = null;
            last_selectedRows = (((DevExpress.XtraEditors.GridLookUpEditBase)(sender)).Properties).View.GetSelectedRows();
            Allowclose = false;
        }

        public override string EditorTypeName
        {
            get
            {
                return
                        RepositoryItemMyGridLookUpEdit.MyGridLookUpEditName;
            }
        }


        [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
        public new RepositoryItemMyGridLookUpEdit Properties
        {
            get { return base.Properties as RepositoryItemMyGridLookUpEdit; }
        }

    }
}

Và source code sử dụng control ở FrmMain:

using DevExpress.Utils.Win;
using DevExpress.XtraEditors;
using DevExpress.XtraEditors.Controls;
using DevExpress.XtraEditors.Repository;
using DevExpress.XtraEditors.ViewInfo;
using DevExpress.XtraGrid.Views.Grid;
using DevExpress.XtraGrid.Views.Grid.ViewInfo;
using DevExpress.XtraLayout;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlTypes;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace multiselectcontrol
{
    public partial class Form1 : DevExpress.XtraEditors.XtraForm
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {       
            var data = new DataTable();
            data.Columns.Add("id", typeof(string));
            data.Columns.Add("name", typeof(string));
            data.Columns.Add("address", typeof(string));
            data.Rows.Add("MASV001", "Nguyễn Thảo", "Vũng Tàu");
            data.Rows.Add("MASV002", "Nguyễn Đình Tuyên", "Quảng Bình");
            data.Rows.Add("MASV003", "Nguyễn Phương Nhi", "Kiên Giang");
            data.Rows.Add("MASV004", "Nguyễn Thị Cẩm Tú", "TP.HCM");
            data.Rows.Add("MASV005", "Cái Trí Minh", "Đồng Nai");
            data.Rows.Add("MASV006", "Võ Sơn Băng", "Vĩnh Long");
            multiSelectLookUpEdit1.Properties.DataSource = data;
            multiSelectLookUpEdit1.Properties.ValueMember = "id";
            multiSelectLookUpEdit1.Properties.DisplayMember = "name";         
        }


   
        private void multiSelectLookUpEdit1_MultiValueChanged(object sender, EventArgs e)
        {
            lbl_result.Text = multiSelectLookUpEdit1.VALUE;
        }

     
    }
}

Thanks for watching!

DOWNLOAD SOURCE

THÔNG TIN TÁC GIẢ

BÀI VIẾT LIÊN QUAN

[DEVEXPRESS] Thừa kế control SearchLookupEdit thành MultiSelectGridLookupEdit
Đăng bởi: Thảo Meo - Lượt xem: 8454 19:51:17, 08/10/2020C#   In bài viết

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

Đọc tiếp
.