Bài viết mới

[DEVEXPRESS] Hướng dẫn chọn nhiều dòng multi select trong GridLookupEdit

[DEVEXPRESS] Hướng dẫn chọn nhiều dòng multi select trong GridLookupEdit
Đăng bởi: Thảo meo - Lượt xem: 296 09:45:38, 29/11/2018DEVEXPRESS   In bài viết

Xin chào các bạn, bài viết hôm nay mình sẽ hướng dẫn các bạn cách chọn nhiều dòng dữ liệu trong GridLookupEdit của Devexpress C#.

Trong công cụ mặc định GridLookupEdit của Devexpress, bạn không thể chọn nhiều dòng trên Gridview của nó, và lấy những dữ liệu mình mới chọn được.

Muốn chọn được nhiều dòng mình cần phải custom lại component GridLookupEdit lại.

Để chọn được nhiều dòng, các bạn cần enable cho phép GridLookupEdit ở chế độ Multiselect lên.

Dưới đây là demo ứng dụng chọn nhiều dòng:

multi_select_gridlookupedit

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

Source code C#:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
using DevExpress.XtraEditors.Repository;
using DevExpress.XtraGrid.Views.Grid;
using DevExpress.XtraGrid.Views.Base;
using System.Windows.Forms;
using DevExpress.Utils.Drawing;
using DevExpress.XtraGrid.Views.Grid.ViewInfo;
using System.Drawing;
using DevExpress.XtraGrid.Columns;

namespace MuaBan.Net
{
    public class GridCheckMarksSelection
    {
        RepositoryItemGridLookUpEdit _currentRepository;

        protected ArrayList selection;
        protected string checkColumnFieldName = "CheckMarkSelection";
        RepositoryItemCheckEdit edit;
        const int CheckboxIndent = 4;

        public GridCheckMarksSelection(RepositoryItemGridLookUpEdit repository) : this()
        {
            CurrentRepository = repository; 
        }

        public RepositoryItemGridLookUpEdit CurrentRepository
        {
            get { return _currentRepository; }
            set {
                if (_currentRepository != value)
                {
                    Detach();
                    Attach(value);
                }
            }
        }

        public GridCheckMarksSelection()
        {
            selection = new ArrayList();
            this.OnSelectionChanged();
        }

        public ArrayList Selection
        {
            get { return selection; }
            set { selection = value; }
        }

        public int SelectedCount { get { return selection.Count; } }

        public object GetSelectedRow(int index)
        { return selection[index]; }

        public int GetSelectedIndex(object row)
        { return selection.IndexOf(row); }

        public void ClearSelection(GridView currentView)
        {
            selection.Clear();
            Invalidate(currentView);
            OnSelectionChanged();
        }

        public void SelectAll(object sourceObject)
        {
            selection.Clear();
            if (sourceObject != null)
            {
                if (sourceObject is ICollection)
                    selection.AddRange(((ICollection)sourceObject));
                else
                {
                    GridView currentView = sourceObject as GridView;
                    for (int i = 0; i < currentView.DataRowCount; i++)
                        selection.Add(currentView.GetRow(i));
                    Invalidate(currentView);
                }
            }
            this.OnSelectionChanged();
        }


        public delegate void SelectionChangedEventHandler(object sender, EventArgs e);
        public event SelectionChangedEventHandler SelectionChanged;
        public void OnSelectionChanged()
        {
            if (SelectionChanged != null)
            {
                EventArgs e = new EventArgs();
                SelectionChanged(this, e);
            }
        }
        public void SelectGroup(GridView currentView, int rowHandle, bool select)
        {
            if (IsGroupRowSelected(currentView, rowHandle) && select) return;
            for (int i = 0; i < currentView.GetChildRowCount(rowHandle); i++)
            {
                int childRowHandle = currentView.GetChildRowHandle(rowHandle, i);
                if (currentView.IsGroupRow(childRowHandle))
                    SelectGroup(currentView, childRowHandle, select);
                else
                    SelectRow(currentView, childRowHandle, select, false);
            }
            Invalidate(currentView);
        }

        public void SelectRow(GridView currentView, int rowHandle, bool select)
        { 
            SelectRow(currentView, rowHandle, select, true); 
        }

        public void InvertRowSelection(GridView currentView, int rowHandle)
        {
            if (currentView.IsDataRow(rowHandle))
                SelectRow(currentView, rowHandle, !IsRowSelected(currentView, rowHandle));
            if (currentView.IsGroupRow(rowHandle))
                SelectGroup(currentView, rowHandle, !IsGroupRowSelected(currentView, rowHandle));
        }
        public bool IsGroupRowSelected(GridView currentView, int rowHandle)
        {
            for (int i = 0; i < currentView.GetChildRowCount(rowHandle); i++)
            {
                int row = currentView.GetChildRowHandle(rowHandle, i);
                if (currentView.IsGroupRow(row))
                {
                    if (!IsGroupRowSelected(currentView, row)) return false;
                }
                else
                    if (!IsRowSelected(currentView, row)) return false;
            }
            return true;
        }
        public bool IsRowSelected(GridView currentView, int rowHandle)
        {
            if (currentView.IsGroupRow(rowHandle))
                return IsGroupRowSelected(currentView, rowHandle);

            object row = currentView.GetRow(rowHandle);
            return GetSelectedIndex(row) != -1;
        }

        protected virtual void Attach(RepositoryItemGridLookUpEdit rep)
        {
            if (rep == null) return;
            selection.Clear();
            _currentRepository = rep;

            edit = _currentRepository.View.GridControl.RepositoryItems.Add("CheckEdit") as RepositoryItemCheckEdit;

            GridColumn column = _currentRepository.View.Columns.Add();
            column.OptionsColumn.AllowSort = DevExpress.Utils.DefaultBoolean.False;
            column.Visible = true;
            column.VisibleIndex = 0;
            column.FieldName = checkColumnFieldName;
            column.Caption = "Mark";
            column.OptionsColumn.ShowCaption = false;
            column.OptionsColumn.AllowEdit = false;
            column.OptionsColumn.AllowSize = false;
            column.UnboundType = DevExpress.Data.UnboundColumnType.Boolean;
            column.Width = GetCheckBoxWidth();
            column.ColumnEdit = edit;

            _currentRepository.View.Click += new EventHandler(View_Click);
            _currentRepository.View.CustomDrawColumnHeader += new ColumnHeaderCustomDrawEventHandler(View_CustomDrawColumnHeader);
            _currentRepository.View.CustomDrawGroupRow += new RowObjectCustomDrawEventHandler(View_CustomDrawGroupRow);
            _currentRepository.View.CustomUnboundColumnData += new CustomColumnDataEventHandler(view_CustomUnboundColumnData);
            _currentRepository.View.KeyDown += new KeyEventHandler(view_KeyDown);
        }

        protected virtual void Detach()
        {
            if (_currentRepository == null) return;
            if (edit != null)
            {
                _currentRepository.View.GridControl.RepositoryItems.Remove(edit);
                edit.Dispose();
            }
            _currentRepository.View.Click -= new EventHandler(View_Click);
            _currentRepository.View.CustomDrawColumnHeader -= new ColumnHeaderCustomDrawEventHandler(View_CustomDrawColumnHeader);
            _currentRepository.View.CustomDrawGroupRow -= new RowObjectCustomDrawEventHandler(View_CustomDrawGroupRow);
            _currentRepository.View.CustomUnboundColumnData -= new CustomColumnDataEventHandler(view_CustomUnboundColumnData);
            _currentRepository.View.KeyDown -= new KeyEventHandler(view_KeyDown);
            _currentRepository = null;
        }
        protected int GetCheckBoxWidth()
        {
            DevExpress.XtraEditors.ViewInfo.CheckEditViewInfo info = edit.CreateViewInfo() as DevExpress.XtraEditors.ViewInfo.CheckEditViewInfo;
            int width = 0;
            GraphicsInfo.Default.AddGraphics(null);
            try
            {
                width = info.CalcBestFit(GraphicsInfo.Default.Graphics).Width;
            }
            finally
            {
                GraphicsInfo.Default.ReleaseGraphics();
            }
            return width + CheckboxIndent * 2;
        }

        protected void DrawCheckBox(Graphics g, Rectangle r, bool Checked)
        {
            DevExpress.XtraEditors.ViewInfo.CheckEditViewInfo info;
            DevExpress.XtraEditors.Drawing.CheckEditPainter painter;
            DevExpress.XtraEditors.Drawing.ControlGraphicsInfoArgs args;
            info = edit.CreateViewInfo() as DevExpress.XtraEditors.ViewInfo.CheckEditViewInfo;
            painter = edit.CreatePainter() as DevExpress.XtraEditors.Drawing.CheckEditPainter;
            info.EditValue = Checked;
            info.Bounds = r;
            info.CalcViewInfo(g);
            args = new DevExpress.XtraEditors.Drawing.ControlGraphicsInfoArgs(info, new DevExpress.Utils.Drawing.GraphicsCache(g), r);
            painter.Draw(args);
            args.Cache.Dispose();
        }

        void Invalidate(GridView currentView)
        {
            currentView.BeginUpdate();
            currentView.EndUpdate();
        }
        void SelectRow(GridView currentView, int rowHandle, bool select, bool invalidate)
        {
            if (IsRowSelected(currentView, rowHandle) == select) return;
            object row = currentView.GetRow(rowHandle);
            if (select)
                selection.Add(row);
            else
                selection.Remove(row);
            if (invalidate)
                Invalidate(currentView);
            OnSelectionChanged();
        }
        void view_CustomUnboundColumnData(object sender, CustomColumnDataEventArgs e)
        {
            GridView currentView = sender as GridView;
            if (e.Column != null && e.Column.FieldName == checkColumnFieldName)
            {
                if (e.IsGetData)
                    e.Value = IsRowSelected(currentView, currentView.GetRowHandle(e.ListSourceRowIndex));
                else
                    SelectRow(currentView, currentView.GetRowHandle(e.ListSourceRowIndex), (bool)e.Value);
            }
        }
        void view_KeyDown(object sender, KeyEventArgs e)
        {
            GridView currentView = sender as GridView;
            if (currentView.FocusedColumn.FieldName != checkColumnFieldName || e.KeyCode != Keys.Space) return;
            InvertRowSelection(currentView, currentView.FocusedRowHandle);
        }
        void View_Click(object sender, EventArgs e)
        {
            GridHitInfo info;
            GridView currentView = (sender as GridView);
            Point pt = currentView.GridControl.PointToClient(Control.MousePosition);
            info = currentView.CalcHitInfo(pt);
            if (info.Column != null && info.Column.FieldName == checkColumnFieldName)
            {
                if (info.InColumn)
                {
                    if (SelectedCount == currentView.DataRowCount)
                        ClearSelection(currentView);
                    else
                        SelectAll(currentView);
                }
                if (info.InRowCell)
                    InvertRowSelection(currentView, info.RowHandle);
            }
            if (info.InRow && currentView.IsGroupRow(info.RowHandle) && info.HitTest != GridHitTest.RowGroupButton)
                InvertRowSelection(currentView, info.RowHandle);
        }
        void View_CustomDrawColumnHeader(object sender, ColumnHeaderCustomDrawEventArgs e)
        {
            if (e.Column != null && e.Column.FieldName == checkColumnFieldName)
            {
                e.Info.InnerElements.Clear();
                e.Painter.DrawObject(e.Info);
                DrawCheckBox(e.Graphics, e.Bounds, SelectedCount == (sender as GridView).DataRowCount);
                e.Handled = true;
            }
        }
        void View_CustomDrawGroupRow(object sender, RowObjectCustomDrawEventArgs e)
        {
            DevExpress.XtraGrid.Views.Grid.ViewInfo.GridGroupRowInfo info;
            info = e.Info as DevExpress.XtraGrid.Views.Grid.ViewInfo.GridGroupRowInfo;

            info.GroupText = "         " + info.GroupText.TrimStart();
            e.Info.Paint.FillRectangle(e.Graphics, e.Appearance.GetBackBrush(e.Cache), e.Bounds);
            e.Painter.DrawObject(e.Info);

            Rectangle r = info.ButtonBounds;
            r.Offset(r.Width + CheckboxIndent * 2 - 1, 0);
            DrawCheckBox(e.Graphics, r, IsGroupRowSelected((sender as GridView), e.RowHandle));
            e.Handled = true;
        }
    }
}

 

  • Tiếp theo cần bạn cần viết hai sự kiện cho GridLookupEdit ở Form1.cs

1. Hàm sự kiện gridLookUpEdit1_CustomDisplayText()

private void gridLookUpEdit1_CustomDisplayText(object sender, CustomDisplayTextEventArgs e)
        {
            StringBuilder sb = new StringBuilder();
            StringBuilder sb2 = new StringBuilder();
            GridCheckMarksSelection gridCheckMark = sender is GridLookUpEdit ? (sender as GridLookUpEdit).Properties.Tag as GridCheckMarksSelection :
                                                                                    (sender as RepositoryItemGridLookUpEdit).Tag as GridCheckMarksSelection;

            if (gridCheckMark == null) return;
            foreach (DataRowView f in gridCheckMark.Selection)
            {
                if (sb.ToString().Length > 0) { sb.Append(", "); sb2.Append("|"); }
                DataRow row = ((DataRowView)f).Row;

                sb.Append(row[4]);
                sb2.Append(row[1]);
            }
            e.DisplayText = sb.ToString();
            lbl_link_select.Text = sb2.ToString();
        }

2. Hàm sự kiện gridCheckMarks_SelectionChanged

Source code C#:

void gridCheckMarks_SelectionChanged(object sender, EventArgs e)
        {
            if (ActiveControl is GridLookUpEdit)
            {
                StringBuilder sb = new StringBuilder();
                StringBuilder sb2 = new StringBuilder();
                foreach (DataRowView f in (sender as GridCheckMarksSelection).Selection)
                {
                    if (sb.ToString().Length > 0) { sb.Append(", "); sb2.Append("|"); }


                    DataRow row = ((DataRowView)f).Row;

                    sb.Append(row[4]);
                    sb2.Append(row[1]);

                }
                (ActiveControl as GridLookUpEdit).Text = sb.ToString();
                lbl_link_select.Text = sb2.ToString();
            }

3. Và cuối cùng chúng ta sẽ add sự kiện vào dữ liệu vào GridLookupEdit

GridCheckMarksSelection gridCheckMarksSA;
private void Form1_Load(object sender, EventArgs e)
{

    DataProvider provider = new DataProvider();
    string query = $"select * from tbl_addsite  order by id asc";
    DataTable dt = provider.ExecuteQuery(query);
   

    gridLookUpEdit1.Properties.DataSource = dt;
    gridLookUpEdit1.Properties.ValueMember = "link";
    gridLookUpEdit1.Properties.DisplayMember = "id";
    gridLookUpEdit1.CustomDisplayText += new CustomDisplayTextEventHandler(gridLookUpEdit1_CustomDisplayText);
    gridLookUpEdit1.Properties.PopulateViewColumns();


    gridCheckMarksSA = new GridCheckMarksSelection(gridLookUpEdit1.Properties);


    gridCheckMarksSA.SelectionChanged += new GridCheckMarksSelection.SelectionChangedEventHandler(gridCheckMarks_SelectionChanged);
    gridLookUpEdit1.Properties.Tag = gridCheckMarksSA;


}

HAVE FUN :)

DOWNLOAD SOURCE

Tags: multi select gridlookupeditgridlookupedit

BÀI VIẾT LIÊN QUAN

[DEVEXPRESS] Hướng dẫn chọn nhiều dòng multi select trong GridLookupEdit
Đăng bởi: Thảo meo - Lượt xem: 296 09:45:38, 29/11/2018DEVEXPRESS   In bài viết

THẢO LUẬN BÀI VIẾT

PHẦN MỀM LẤY TIN BẤT ĐỘNG SẢN

phần mềm lấy tin tự động bất động sản

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

Đọc tiếp
.