Hiển thị các bài đăng có nhãn DEVEXPRESS. Hiển thị tất cả bài đăng
Hiển thị các bài đăng có nhãn DEVEXPRESS. Hiển thị tất cả bài đăng

[DEVEXPRESS] Search and Custom Highlight Text in Winform C#

[DEVEXPRESS] Search and Custom Highlight Text in Winform C#

Xin chào các bạn, bài viết hôm nay mình chia sẻ các bạn cách tìm kiếm Tiếng Việt không dấu highlight có dấu trên Devexpress Winform C#.

[DEVEXPRESS] Tìm kiếm không dấu tô màu highlight có dấu trên C# Winform


Hình ảnh tìm kiếm không dấu có thể highlight có dấu Tiếng Việt:

Ở hình ảnh trên, các bạn thấy mình gõ vào từ khóa: cam thuy quang
=> kết quả nó tự hiểu và tìm kiếm Cam Thủy, Quảng Bình...

Video demo ứng dụng:


FULL SOURCE CODE CSHARP:

using DevExpress.XtraEditors.Controls;
using Newtonsoft.Json;
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
using System.Windows.Forms;
using System.Text.RegularExpressions;
using System.Diagnostics;
using System.Globalization;
using DevExpress.Utils.Paint;
using DevExpress.XtraGrid.Views.Base;
using DevExpress.Utils.Html.Internal;
using DevExpress.XtraPrinting.Native;
using DevExpress.XtraPrinting;
using DevExpress.XtraEditors;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;

namespace SearchHighLightNoneVietnamese
{
    public partial class Form1 : DevExpress.XtraEditors.XtraForm
    {
        private List<DVHC> listDVHC = new List<DVHC>();
        public Color foreColorHighLight = Color.White;
        public Color backgroundColorHighLight = Color.YellowGreen;
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            colorBackground.Color = backgroundColorHighLight;
            colorForeground.Color = foreColorHighLight;
        }
        protected override void OnShown(EventArgs e)
        {
            base.OnShown(e);
            var jsonRawData = File.ReadAllText("data.json");
            listDVHC = JsonConvert.DeserializeObject<List<DVHC>>(jsonRawData);
            cb_diadiem.Properties.DataSource = listDVHC;
            cb_diadiem.AutoSuggest += repositoryItemGridLookUpEdit1_AutoSuggest;
            gridLookUpEdit1View.CustomDrawCell += cbDiadiem_CustomDrawCell;
            cb_diadiem.Properties.ValueMember = "maxa";
            cb_diadiem.Properties.DisplayMember = "diadiem";
            cb_diadiem.Properties.PopupFormSize = new System.Drawing.Size(cb_diadiem.Width, 300);
            cb_diadiem.BeforePopup += Cb_diadiem_BeforePopup;
            cb_diadiem.Popup += Cb_diadiem_Popup;
            LoadTinhThanh();
            LoadQuanHuyen();
            LoadPhuongXa();
            this.KeyPreview = true;
            this.KeyDown += Form1_KeyDown;
        }

        private void Cb_diadiem_Popup(object sender, EventArgs e)
        {
            gridLookUpEdit1View.CustomDrawCell += cbDiadiem_CustomDrawCell;
        }

        private void Cb_diadiem_BeforePopup(object sender, EventArgs e)
        {
            gridLookUpEdit1View.CustomDrawCell -= cbDiadiem_CustomDrawCell;
        }

        private void Form1_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Control && e.KeyCode == Keys.K)
            {
                cb_diadiem.Focus();
                cb_diadiem.SelectAll();
            }
        }

        public void LoadTinhThanh() {
            var dataTinhThanh = listDVHC.Select(x => new { matinh = x.matinh, tentinh = x.tentinh }).Distinct().ToList();
            cb_tinhthanh.Properties.DataSource = dataTinhThanh;
            cb_tinhthanh.Properties.ValueMember = "matinh";
            cb_tinhthanh.Properties.DisplayMember = "tentinh";
        }

        public void LoadQuanHuyen()
        {
            var dataQuanHuyen = listDVHC.Select(x => new { mahuyen = x.mahuyen, tenhuyen = x.tenhuyen }).Distinct().ToList();
            cb_quanhuyen.Properties.DataSource = dataQuanHuyen;
            cb_quanhuyen.Properties.ValueMember = "mahuyen";
            cb_quanhuyen.Properties.DisplayMember = "tenhuyen";
        }

        public void LoadPhuongXa()
        {
            var dataPhuongXa = listDVHC.Select(x => new { maxa = x.maxa, tenxa = x.tenxa }).Distinct().ToList();
            cb_phuongxa.Properties.DataSource = dataPhuongXa;
            cb_phuongxa.Properties.ValueMember = "maxa";
            cb_phuongxa.Properties.DisplayMember = "tenxa";
        }

        private void cbDiadiem_CustomDrawCell(object sender, RowCellCustomDrawEventArgs e)
        {

            XPaint paint = new XPaint();
            MultiColorDrawStringParams drawParams = new MultiColorDrawStringParams(e.Appearance);


            var searchText = cb_diadiem.Text;



            if (e.DisplayText.Length < searchText.Length)
                return;

            
            drawParams.Bounds = e.Bounds;
            drawParams.Text = e.DisplayText;           
            string tmpStr = e.DisplayText;
           
            var searchIndexesListOrigin = getListIndexMatch(e.DisplayText, searchText);
            if (searchIndexesListOrigin.Count == 0) return;
          

            var searchIndexesList = searchIndexesListOrigin.OrderBy(x => x.Item2).ToList();
            if (searchIndexesList.Count() > 0)
            {
                drawParams.Ranges = new CharacterRangeWithFormat[searchIndexesList.Count() * 2 + 1];
                int currentStrIndex = 0;
                int i = 0;
                while (i < searchIndexesList.Count())
                {
                    drawParams.Ranges[i * 2] = new CharacterRangeWithFormat(currentStrIndex, searchIndexesList[i].Item2 - currentStrIndex, e.Appearance.ForeColor, e.Appearance.BackColor);
                    drawParams.Ranges[i * 2 + 1] = new CharacterRangeWithFormat(searchIndexesList[i].Item2, searchIndexesList[i].Item3 - searchIndexesList[i].Item2, foreColorHighLight, backgroundColorHighLight);
                    currentStrIndex = searchIndexesList[i].Item3;
                    i++;
                }
                drawParams.Ranges[i * 2] = new CharacterRangeWithFormat(currentStrIndex, e.DisplayText.Length - currentStrIndex, e.Appearance.ForeColor, e.Appearance.BackColor);
                drawParams.Ranges = drawParams.Ranges.Where(val => val.Length != 0).ToArray();
            }
            paint.MultiColorDrawString(new DevExpress.Utils.Drawing.GraphicsCache(e.Graphics), drawParams);
            e.Handled = true;
            
        }

        public  int AccentInsensitiveIndexOf(string source, string subStr)
        {
            // return CultureInfo.InvariantCulture.CompareInfo.IndexOf(source, subStr, CompareOptions.IgnoreCase | CompareOptions.IgnoreSymbols | CompareOptions.IgnoreNonSpace);
            var keyword = BoDauTiengViet(subStr);

            //Regex.Match(source, $@"\W{keyword}\W").Index;
            var match = Regex.Match(source, $@"\b{keyword}\b");
            int index = match.Success ? match.Index : -1;
            return index;
        }

       
        public List<(string, int, int)> getListIndexMatch(string source, string subStr)
    {


            var listdata = new List<(string, int, int)>();


            string[] stringSeparators = new string[] { " " };
            var sourceArr = source.Split(stringSeparators, StringSplitOptions.RemoveEmptyEntries);

            var arrKeywork = subStr.Split(stringSeparators, StringSplitOptions.RemoveEmptyEntries);

         

            foreach (string keyword in arrKeywork)
            {
                var start = AccentInsensitiveIndexOf(BoDauTiengViet( source), keyword);
                var end = start + keyword.Length;
                var item = (keyword, start, end);
                if(start >= 0)
                {

                    bool isStartBoundary = (start == 0) || char.IsWhiteSpace(source[start - 1]);
                    bool isEndBoundary = (end == source.Length) || char.IsWhiteSpace(source[end]);

                    //    var stringMatch = source.Substring(start, keyword.Length);

                    //    var isWordMatch = keyword == BoDauTiengViet(stringMatch);
                    //    if (isWordMatch)
                  //  if (isStartBoundary || isEndBoundary) {
                        listdata.Add(item);
                    //}
                   

                }
          

            }
            return listdata;
        }

        public Task<ICollection> QueryAsync(string keywords, CancellationToken cancellation)
        {

            return Task.Run(() =>
            {
                if (!string.IsNullOrEmpty(keywords))
                {
                    return FilterDVHCByKeyWords(listDVHC, keywords) as ICollection;
                }
                else
                {
                    return listDVHC as ICollection;
                }

            });
        }

        private void repositoryItemGridLookUpEdit1_AutoSuggest(object sender, LookUpEditAutoSuggestEventArgs e)
        {
            e.SetMinimumAnimationDuration(TimeSpan.FromMilliseconds(100));
            e.QuerySuggestions = QueryAsync(e.Text, e.CancellationToken);
        }

       
        public List<DVHC> FilterDVHCByKeyWords(List<DVHC> data, string keyworks) {
            string[] pattern_split = new string[] { " " };
            string[] arr_keywords = keyworks.Split(pattern_split, StringSplitOptions.RemoveEmptyEntries);
            var cleanedKeywords = arr_keywords.Select(k => BoDauTiengViet(k));
            var regexPattern = string.Join(".*", cleanedKeywords.Select(Regex.Escape));
            var regex = new Regex(regexPattern, RegexOptions.IgnoreCase);

            return data.Where(item => regex.IsMatch(BoDauTiengViet(item.diadiem))).ToList();
        }

        public string BoDauTiengViet(string str)
        {
            str = str.ToLower().Trim();
            str = Regex.Replace(str, "[àáạảãâầấậẩẫăằắặẳẵ]", "a");
            str = Regex.Replace(str, "[èéẹẻẽêềếệểễ]", "e");
            str = Regex.Replace(str, "[ìíịỉĩ]", "i");
            str = Regex.Replace(str, "[òóọỏõôồốộổỗơờớợởỡ]", "o");
            str = Regex.Replace(str, "[ùúụủũưừứựửữ]", "u");
            str = Regex.Replace(str, "[ỳýỵỷỹ]", "y");
            str = Regex.Replace(str, "đ", "d");
          //  str = Regex.Replace(str, " ", "-");
            str = str.Replace(",", " ");
            str = str.Replace(".", " ");
            return str;
        }

        private void colorForeground_EditValueChanged(object sender, EventArgs e)
        {
            foreColorHighLight = colorForeground.Color;
        }

        private void colorBackground_EditValueChanged(object sender, EventArgs e)
        {
            backgroundColorHighLight = colorBackground.Color;
        }

        private void cb_diadiem_EditValueChanged(object sender, EventArgs e)
        {
            if (cb_diadiem.EditValue != null) {
                
                var selectedRow = cb_diadiem.GetSelectedDataRow() as DVHC; 
                cb_tinhthanh.EditValue = selectedRow.matinh;
                cb_quanhuyen.EditValue = selectedRow.mahuyen;
                cb_phuongxa.EditValue = selectedRow.maxa;
               
            }         

        }
    }



    public class DVHC { 
        public string diadiem { get; set; }
        public string maxa { get; set; }
        public string tenxa { get; set; }
        public string mahuyen { get; set; }
        public string tenhuyen { get; set; }
        public string matinh { get; set; }
        public string tentinh { get; set; }
    }
}

Chúc mọi người thành công với thủ thuật trên.

on Thứ Ba, 16 tháng 7, 2024 | , , , | A comment?

[Visual Basic] Instructions for creating Multi Group Report automatically

Hôm trước, mình đã có viết bài hướng dẫn các bạn tạo report tự động tham chiếu trực tiếp từ câu lệnh SQL server, hôm nay, mình tiếp tục hướng dẫn các bạn cách gom nhóm (tạo group) trong Xtra Report của Devexpress.

Đồng thời mình cũng hướng các bạn cách chèn số thứ tự vào đầu câu lệnh truy vấn SQL Server.
Cú Pháp:
select ROW_NUMBER()OVER(Partition By Country Order By Country DESC) AS [Số thứ tự],
 CustomerID, ContactName, Address, City, Country, PostalCode, Phone, Fax from Customers

Demo dưới này mình hướng dẫn các bạn chi tiết group nhiều field name khác nhau, có thể linh động tùy biến.

Hoặc có thể xem video demo ứng dụng bên dưới.



Bây Giờ chúng ta bắt đầu code từng bước để tạo ra ứng dụng nhé.

Đầu tiên các bạn Import những thư viện này vào.

Imports System
Imports System.Data
Imports System.Drawing
Imports System.Text
Imports System.Windows.Forms
Imports DevExpress
Imports DevExpress.Data
Imports DevExpress.XtraReports.UI
Imports System.Data.SqlClient
Imports DevExpress.XtraPrinting.Drawing
Imports DevExpress.XtraSplashScreen
Imports System.Threading

Tiếp theo tạo hàm kết nối tới database, và tạo hàm trả về một dataset.

Dim con As New SqlConnection
    Public Sub Taoketnoi()
        Dim str As String = "Data Source=.;Initial Catalog=NORTHWND;Integrated Security=True"
        con.ConnectionString = str
        con.Open()
    End Sub
    Public Sub Dongketnoi()
        con.Close()
    End Sub
    Public Function LayDulieu(query As String) As DataSet
        Taoketnoi()
        Dim dt As New DataSet
        Dim da As New SqlDataAdapter
        da.SelectCommand = New SqlCommand(query, con)
        da.Fill(dt)
        Dongketnoi()
        Return dt
    End Function

Viết sự kiện cho nút tạo Report

Private Sub btnCreateReport_Click(sender As Object, e As EventArgs) Handles btnCreateReport.Click
        SplashScreenManager.ShowForm(Me, GetType(loading), True, True, False)
        Dim report As New XtraReport()
        'cấu hình report
        report.PaperKind = System.Drawing.Printing.PaperKind.A4Rotated
        report.Margins = New System.Drawing.Printing.Margins(20, 20, 20, 20)
        'end cấu hình report
        Dim dataSet As DataSet = LayDulieu(txtQuery.Text)
        Dim dataTable As DataTable = dataSet.Tables(0)
        report.DataSource = dataSet
        'report.DataMember = "Customers"

        CreateReportHeader(report, txtTieude.Text, Color.PowderBlue, 32)
        CreateDetailBand(report, dataTable, "", Color.Silver, False)
        If txtFiled1.Text <> "" And txtField2.Text <> "" Then
            CreateGrouping(report, txtField2.Text, txtField2.Text)
            CreateGrouping(report, txtFiled1.Text, txtFiled1.Text)
        ElseIf txtField2.Text <> "" Then
            CreateGrouping(report, txtField2.Text, txtField2.Text)
        ElseIf txtField3.Text <> "" Then
            CreateGrouping(report, txtField3.Text, txtField3.Text)
        ElseIf txtFiled1.Text <> "" Then
            CreateGrouping(report, txtFiled1.Text, txtFiled1.Text)

        End If
        If rdoIsgroup.Text = 0 Then
            SetTextWatermark(report)
        Else
            SetPictureWatermark(report)
        End If
        CreateDetailReportBasedOnSubreport(report)
        report.ShowRibbonPreviewDialog()
        SplashScreenManager.CloseForm(False)
    End Sub

Viết hàm tạo Report Header (tiêu đề của report)

Private Sub CreateReportHeader(ByVal report As XtraReportBase, ByVal caption As String, ByVal labelColor As Color, ByVal fontSize As Integer)
        'Creating a Report header
        Dim header As New ReportHeaderBand()
        report.Bands.Add(header)
        header.HeightF = 0

        Dim label As New XRLabel()
        header.Controls.Add(label)

        label.ForeColor = Color.Green
        label.Font = New Font("Tahoma", 25, FontStyle.Bold)
        label.Text = caption
        label.TextAlignment = DevExpress.XtraPrinting.TextAlignment.TopCenter
        label.LocationF = New PointF(0, 0)

        Dim rep As XtraReport = report.RootReport
        label.WidthF = rep.PageWidth - rep.Margins.Right - rep.Margins.Left
    End Sub

Viết hàm chi tiết nhánh data dữ liệu load vào (table bạn load từ datase lên)

Private Sub CreateDetailBand(ByVal report As XtraReportBase, ByVal templateTable As DataTable, ByVal dataMember As String, ByVal backColor As Color, ByVal useStyles As Boolean)
        Dim detail As New DetailBand()
        report.Bands.Add(detail)

        detail.HeightF = 0

        ' Creating Header and Detail Tables
        Dim headerTable As New XRTable()

        report.Bands(BandKind.ReportHeader).Controls.Add(headerTable)
        headerTable.Height = 40
        Dim detailTable As New XRTable()
        detail.Controls.Add(detailTable)

        detailTable.BeginInit()
        headerTable.BeginInit()

        Dim headerRow As New XRTableRow()
        headerTable.Rows.Add(headerRow)


        Dim detailRow As New XRTableRow()
        detailTable.Rows.Add(detailRow)

        Dim colCount As Integer = templateTable.Columns.Count
        Dim rootReport As XtraReport = report.RootReport
        Dim pageWidth As Integer = (rootReport.PageWidth - (rootReport.Margins.Left + rootReport.Margins.Right))
        Dim colWidth As Single = pageWidth  colCount
        'Creating an XRTableCell for each column in the corresponding DataTable
        For i As Integer = 0 To colCount - 1
            Dim headerCell As New XRTableCell()
            headerRow.Cells.Add(headerCell)
            headerCell.WidthF = colWidth
            headerCell.BackColor = Color.Orange
            headerCell.ForeColor = Color.White
            headerCell.Height = 40
            headerCell.Text = templateTable.Columns(i).Caption
            headerCell.TextAlignment = DevExpress.XtraPrinting.TextAlignment.MiddleLeft
            headerCell.Borders = DevExpress.XtraPrinting.BorderSide.All
            headerCell.Font = New Font("Tahoma", 12, FontStyle.Bold, GraphicsUnit.Pixel)
            headerCell.Padding = New DevExpress.XtraPrinting.PaddingInfo(5, 5, 5, 5, 100.0F)

            Dim detailCell As New XRTableCell()
            detailRow.Cells.Add(detailCell)
            detailCell.WidthF = colWidth
            detailCell.Height = 20
            detailCell.Font = New Font("Tahoma", 12, FontStyle.Regular, GraphicsUnit.Pixel)
            detailCell.Padding = New DevExpress.XtraPrinting.PaddingInfo(5, 5, 5, 5, 100.0F)
            Dim actualDM As String = String.Empty
            If dataMember = String.Empty Then
                actualDM = templateTable.Columns(i).Caption
            Else
                actualDM = String.Format("{0}.{1}", dataMember, templateTable.Columns(i).Caption)
            End If
            detailCell.DataBindings.Add("Text", Nothing, actualDM)
            detailCell.Borders = DevExpress.XtraPrinting.BorderSide.Left Or DevExpress.XtraPrinting.BorderSide.Bottom Or DevExpress.XtraPrinting.BorderSide.Right
        Next i

        headerTable.EndInit()
        detailTable.EndInit()

        headerTable.LocationF = New PointF(0, report.Bands(BandKind.ReportHeader).HeightF)
        headerTable.WidthF = pageWidth
        headerTable.Font = New Font(headerTable.Font, FontStyle.Bold)

        detailTable.LocationF = New PointF(0, 0)
        detailTable.WidthF = pageWidth
    End Sub

Tiếp tục, lập trình cho hàm tạo Group theo điều kiện mình lựa chọn

Private Sub CreateGrouping(ByVal report As XtraReport, fieldname As String, tieude As String)
        'Add a group to the RootReport
        Dim groupband As New GroupHeaderBand()
        report.Bands.Add(groupband)
        groupband.Height = 30
        groupband.WidthF = 40
        groupband.GroupUnion = GroupUnion.WithFirstDetail


        groupband.GroupFields.Add(New GroupField(fieldname))

        Dim label As New XRLabel()
        groupband.Controls.Add(label)

        label.DataBindings.Add("Text", Nothing, fieldname, tieude & ": {0}")
        label.TextAlignment = DevExpress.XtraPrinting.TextAlignment.MiddleLeft
        label.LocationF = New PointF(0, 0)
        label.WidthF = report.PageWidth - report.Margins.Right - report.Margins.Left
        label.Height = 30
        label.BackColor = Color.Gray
        label.ForeColor = Color.White
        label.Font = New Font("Tahoma", 12, FontStyle.Regular, GraphicsUnit.Pixel)
        label.Padding = New DevExpress.XtraPrinting.PaddingInfo(5, 5, 5, 5, 100.0F)
        label.Borders = DevExpress.XtraPrinting.BorderSide.Left Or DevExpress.XtraPrinting.BorderSide.Right Or DevExpress.XtraPrinting.BorderSide.Bottom
    End Sub

Viết hàm tạo subReport

Private Sub CreateDetailReportBasedOnSubreport(ByVal report As XtraReport)
        'Create a Subreport
        Dim subreport As New XRSubreport()
        Dim detailBand As DetailBand = TryCast(report.Bands(BandKind.Detail), DetailBand)
        detailBand.Controls.Add(subreport)

        subreport.LocationF = New PointF(0, detailBand.HeightF)
        subreport.WidthF = report.PageWidth - report.Margins.Right - report.Margins.Left
        'Create a detail Report
        Dim detailReport As New XtraReport() With {.DataSource = report.DataSource, .DataMember = "Orders"}
        subreport.ReportSource = detailReport
    End Sub

Tiếp tục viết 2 hàm tạo Water mask dạng Text và dạng Picture

Sub SetTextWatermark(ps As XtraReport)
        ' Create the text watermark.
        Dim textWatermark As New Watermark()

        ' Set watermark options.
        textWatermark.Text = "HTTP://LAPTRINHVB.NET"
        textWatermark.TextDirection = DirectionMode.ForwardDiagonal
        textWatermark.Font = New Font(textWatermark.Font.FontFamily, 40)
        textWatermark.ForeColor = Color.DodgerBlue
        textWatermark.TextTransparency = 150
        textWatermark.ShowBehind = False
        textWatermark.PageRange = "1,3-5"

        ' Add the watermark to a document.
        ps.Watermark.CopyFrom(textWatermark)
    End Sub

    Public Sub SetPictureWatermark(ps As XtraReport)
        ' Create the picture watermark.
        Dim pictureWatermark As New Watermark()

        ' Set watermark options.
        pictureWatermark.Image = Bitmap.FromFile("logo.png")
        pictureWatermark.ImageAlign = ContentAlignment.MiddleCenter
        pictureWatermark.ImageTiling = False
        pictureWatermark.ImageViewMode = ImageViewMode.Zoom
        pictureWatermark.ImageTransparency = 150
        pictureWatermark.ShowBehind = True
        'pictureWatermark.PageRange = "2,4"

        ' Add the watermark to a document.
        ps.Watermark.CopyFrom(pictureWatermark)
    End Sub
    
Chúc mọi người thành công với thủ thuật trên.

on Thứ Ba, 21 tháng 5, 2024 | , | A comment?

[VISUAL BASIC] Share source code for revenue and expenditure management of Winform 3-layer model


Xin chào các bạn, bài viết hôm nay mình chia sẻ các bạn source code quản lý thu chi đơn giản theo mô hình 3 lớp (3 tier) VB.NET winform.

[CSHARP] Ứng dụng Quản Lý Thu Chi 3 lớp Sqlserver.

Hình ảnh project 3 lớp:

Những chức năng chính của ứng dụng:
  1. Quản lý nhân viên
  2. Quản lý tài khoản đăng nhập
  3. Quản lý tiền thu và tiền chi
  4. Có thể tìm kiểm theo ngày
  5. Xuất báo cáo ra file Excel
Bài viết sử dụng Sqlserver 2012 trở lên và công cụ Devexpress.

Tài khoản đăng nhập:
User:admin
Password:admin

Chi tiết ứng dụng, các bạn có thể tham khảo video:

Bên dưới là hình ảnh sau khi đăng nhập thành công vào chương trình.

Cảm ơn các bạn đã xem, mọi người có thể tải mã nguồn bên dưới để tìm hiểu để phát triển chương trình làm một chương trình bán hàng tốt nhất nhé.

on Thứ Tư, 8 tháng 5, 2024 | , , , | A comment?

[DEVEXPRESS] How to use TreeList with Checkbox in C# Winform

Xin chào các bạn, bài viết hôm nay mình chia sẻ các bạn cách sử dụng Treelist với Checkbox trên Devepxress lập trình C#, Winform. 

 [DEVEXPRESS] Hướng dẫn sử dụng TreeList Checkbox trên C# winform 

 Dưới đây, là hình ảnh demo ứng dụng:


Ở ví dụ, mình sẻ hiển thị danh sách đơn vị hành chính của nước Việt Nam, và khi chúng ta check một tỉnh thành, nó sẽ chọn hết tất cả các nhánh con của nó. Chi tiết, các bạn có thể tham khảo video dưới đây:

Source code c#:

using DevExpress.XtraEditors;
using DevExpress.XtraTreeList.Nodes;
using DevExpress.XtraTreeList;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

using Newtonsoft.Json;
using System.IO;

namespace TreeListCheckBox
{
    public partial class FrmTreeQuyHoach : DevExpress.XtraEditors.XtraForm
    {
        
        public FrmTreeQuyHoach()
        {
            InitializeComponent();
            treeQuyHoach.GetStateImage += TreeQuyHoach_GetStateImage;       
            treeQuyHoach.AfterCheckNode += treeList1_AfterCheckNode;
           // treeQuyHoach.DoubleClick += TreeQuyHoach_DoubleClick;
           
        }

        private void TreeQuyHoach_DoubleClick(object sender, EventArgs e)
        {
            TreeList tree = sender as TreeList;
            TreeListHitInfo hi = tree.CalcHitInfo(tree.PointToClient(Control.MousePosition));
            if (hi.Node != null)
            {
                hi.Node.Checked = !hi.Node.Checked;

                SetChildNodesCheckedState(hi.Node, hi.Node.CheckState);
            }
        }

      

        private void SetChildNodesCheckedState(TreeListNode parentNode, CheckState checkedState)
        {
            foreach (TreeListNode childNode in parentNode.Nodes)
            {
                childNode.Checked = checkedState == CheckState.Checked;

                if (childNode.HasChildren)
                {
                    SetChildNodesCheckedState(childNode, checkedState); 
                }
            }
        }

     

        private void treeList1_AfterCheckNode(object sender, DevExpress.XtraTreeList.NodeEventArgs e)
        {
            SetChildNodesCheckedState(e.Node, e.Node.CheckState);
        }

        private void TreeQuyHoach_GetStateImage(object sender, DevExpress.XtraTreeList.GetStateImageEventArgs e)
        {
            e.NodeImageIndex = e.Node.Level;
        }

        private void FrmTreeQuyHoach_Load(object sender, EventArgs e)
        {
            LoadDataToTreeView();

        }
       

        private void LoadDataToTreeView()
        {
            var jdata = File.ReadAllText("DVHC-data.json");
            var data = JsonConvert.DeserializeObject<List<DVHC>>(jdata);
            treeQuyHoach.KeyFieldName = "id";
            treeQuyHoach.ParentFieldName = "parent_id";
            treeQuyHoach.DataSource = data;
           // treeQuyHoach.ExpandAll();
            treeQuyHoach.ExpandToLevel(0);
            treeQuyHoach.OptionsView.ShowTreeLines = DevExpress.Utils.DefaultBoolean.True;
            treeQuyHoach.Appearance.FocusedCell.BackColor = SystemColors.Highlight;
            treeQuyHoach.Appearance.FocusedCell.ForeColor = SystemColors.HighlightText;
            treeQuyHoach.OptionsView.ShowCheckBoxes = true;
            
            treeQuyHoach.CustomDrawNodeCheckBox += treeList_CustomDrawNodeCheckBox;
          
        }

        public class DVHC
        {
            public string id { get; set; }
            public string parent_id { get; set; }
            public string name { get; set; }

        }

        void treeList_CustomDrawNodeCheckBox(object sender, CustomDrawNodeCheckBoxEventArgs e)
        {
            var d = e.Bounds;

            if (e.Info.CheckState == CheckState.Checked)
            {
                
                e.Cache.DrawImage(Properties.Resources.check_box, new Rectangle(e.Bounds.X, e.Bounds.Y, 18, 18));
            }
            else
            {
                e.Cache.DrawImage(Properties.Resources.check_box_empty, new Rectangle(e.Bounds.X, e.Bounds.Y, 18, 18));
            }

          
            e.Handled = true;
 
            //if (e.Node.HasChildren)
            //{
            //    int x2 = e.Bounds.Left + treeQuyHoach.ViewInfo.RC.LevelWidth / 2;
            //    int y2 = e.Bounds.Top + e.Bounds.Height / 2;
            //    int h2 = e.Bounds.Height / 2 + 1;
            //    Rectangle r1 = new Rectangle(e.Bounds.Left, y2, e.Bounds.Width, 1);
            //    Rectangle r2 = new Rectangle(x2, y2, 1, h2);
            //    Brush brush = treeQuyHoach.ViewInfo.RC.TreeLineBrush == null ? Brushes.Transparent : treeQuyHoach.ViewInfo.RC.TreeLineBrush;
            //    e.Graphics.FillRectangle(brush, r1);
            //    if (e.Node.Expanded)
            //    {
            //        e.Graphics.FillRectangle(brush, r2);
            //    }
            //    e.Handled = true;
            //}
        }

        private void btnRefresh_Click(object sender, EventArgs e)
        {
            LoadDataToTreeView();
        }

        private void simpleButton1_Click(object sender, EventArgs e)
        {

            List<object> checkedNodes = new List<object>();
            foreach (TreeListNode node in treeQuyHoach.Nodes)
            {
                if (node.CheckState == CheckState.Checked)
                {
                    checkedNodes.Add(node.GetValue("name"));
                }
                CheckChildNodes(node, checkedNodes);
            }

            // Use the checkedNodes list as needed

            var message = string.Join(",", checkedNodes);
            MessageBox.Show(message);
        }

        private void CheckChildNodes(TreeListNode node, List<object> checkedNodes)
        {
            foreach (TreeListNode childNode in node.Nodes)
            {
                if (childNode.CheckState == CheckState.Checked)
                {
                    checkedNodes.Add(childNode.GetValue("name"));
                    //checkedNodes.Add(childNode.GetValue("id")); id, code, parent_id, name lấy gì thì truyền vào đó
                }
                CheckChildNodes(childNode, checkedNodes);
            }
        }
    }


 }

Ở ví dụ, các bạn có thể thay đổi icon check và unchecked trên treelist như video mình demo.
Cảm ơn các bạn đã xem.

on Thứ Hai, 6 tháng 5, 2024 | , , , | A comment?

[DEVEXPRESS] Share code to create reports to print multiple invoices on XtraReport C#


Xin chào các bạn, bài viết hôm nay mình chia sẻ các bạn source code các in nhiều hóa đơn cùng một lúc trong Xtrareport Devexpress C#.

[DEVEXPRESS] Chia sẻ code các tạo report in nhiều hóa đơn trên XtraReport C#

Kết quả khi chạy ứng dụng:

Ở bài viết này mình demo 2 loại: List Object và Dataset.

FULL SOURCE CODE C#

using DevExpress.XtraPrinting.Preview;
using DevExpress.XtraPrintingLinks;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraPrinting;
using DevExpress.XtraPrinting.Links;

using DevExpress.XtraReports.UI;

namespace PrintInvoice
{
    public partial class MainForm : DevExpress.XtraEditors.XtraForm
    {
        public MainForm()
        {
            InitializeComponent();
        }

        public List<Invoice> GetSampleData()
        {
            List<Invoice> invoices = new List<Invoice>
    {
        new Invoice
        {
            InvoiceNo = 1001,
            InvoiceDate = new DateTime(2023, 4, 15),
            CustomerName = "Nguyễn Thảo",
            TotalAmount = 1250.75m,
            InvoiceItems = new List<InvoiceItem>
            {
                new InvoiceItem { ItemName = "Product A", Quantity = 2, UnitPrice = 100.50m, TotalPrice = 201.00m },
                new InvoiceItem { ItemName = "Product B", Quantity = 5, UnitPrice = 75.25m, TotalPrice = 376.25m },
                new InvoiceItem { ItemName = "Product C", Quantity = 3, UnitPrice = 224.50m, TotalPrice = 673.50m }
            }
        },
        new Invoice
        {
            InvoiceNo = 1002,
            InvoiceDate = new DateTime(2023, 4, 18),
            CustomerName = "Cái Trí Minh",
            TotalAmount = 875.40m,
            InvoiceItems = new List<InvoiceItem>
            {
                new InvoiceItem { ItemName = "Product D", Quantity = 1, UnitPrice = 375.60m, TotalPrice = 375.60m },
                new InvoiceItem { ItemName = "Product E", Quantity = 4, UnitPrice = 124.95m, TotalPrice = 499.80m }
            }
        },
        new Invoice
        {
            InvoiceNo = 1003,
            InvoiceDate = new DateTime(2023, 4, 20),
            CustomerName = "Võ Sơn Băng",
            TotalAmount = 1500.00m,
            InvoiceItems = new List<InvoiceItem>
            {
                new InvoiceItem { ItemName = "Product F", Quantity = 3, UnitPrice = 200.00m, TotalPrice = 600.00m },
                new InvoiceItem { ItemName = "Product G", Quantity = 2, UnitPrice = 150.75m, TotalPrice = 301.50m },
                new InvoiceItem { ItemName = "Product H", Quantity = 1, UnitPrice = 500.25m, TotalPrice = 500.25m }
            }
        },
        new Invoice
        {
            InvoiceNo = 1004,
            InvoiceDate = new DateTime(2023, 4, 22),
            CustomerName = "Nguyễn Đình Tuyên",
            TotalAmount = 990.50m,
            InvoiceItems = new List<InvoiceItem>
            {
                new InvoiceItem { ItemName = "Product I", Quantity = 2, UnitPrice = 110.25m, TotalPrice = 220.50m },
                new InvoiceItem { ItemName = "Product J", Quantity = 3, UnitPrice = 75.00m, TotalPrice = 225.00m },
                new InvoiceItem { ItemName = "Product K", Quantity = 4, UnitPrice = 140.00m, TotalPrice = 560.00m }
            }
        },
        new Invoice
        {
            InvoiceNo = 1005,
            InvoiceDate = new DateTime(2023, 4, 25),
            CustomerName = "Hoàng Thị Thảo",
            TotalAmount = 675.80m,
            InvoiceItems = new List<InvoiceItem>
            {
                new InvoiceItem { ItemName = "Product L", Quantity = 1, UnitPrice = 375.80m, TotalPrice = 375.80m },
                new InvoiceItem { ItemName = "Product M", Quantity = 2, UnitPrice = 150.00m, TotalPrice = 300.00m }
            }
        },
        new Invoice
        {
            InvoiceNo = 1006,
            InvoiceDate = new DateTime(2023, 4, 28),
            CustomerName = "Nguyễn Phương Nhi",
            TotalAmount = 1150.25m,
            InvoiceItems = new List<InvoiceItem>
            {
                new InvoiceItem { ItemName = "Product N", Quantity = 3, UnitPrice = 200.25m, TotalPrice = 600.75m },
                new InvoiceItem { ItemName = "Product O", Quantity = 2, UnitPrice = 175.50m, TotalPrice = 351.00m },
                new InvoiceItem { ItemName = "Product P", Quantity = 1, UnitPrice = 275.00m, TotalPrice = 275.00m }
            }
        },
        new Invoice
        {
            InvoiceNo = 1007,
            InvoiceDate = new DateTime(2023, 5, 1),
            CustomerName = "Trịnh Quốc Khang",
            TotalAmount = 1450.60m,
            InvoiceItems = new List<InvoiceItem>
            {
                new InvoiceItem { ItemName = "Product Q", Quantity = 4, UnitPrice = 150.50m, TotalPrice = 602.00m },
                new InvoiceItem { ItemName = "Product R", Quantity = 2, UnitPrice = 175.75m, TotalPrice = 351.50m },
                new InvoiceItem { ItemName = "Product S", Quantity = 1, UnitPrice = 500.10m, TotalPrice = 500.10m }
            }
        },
        new Invoice
        {
            InvoiceNo = 1008,
            InvoiceDate = new DateTime(2023, 5, 4),
            CustomerName = "Đinh Minh Thành",
            TotalAmount = 970.25m,
            InvoiceItems = new List<InvoiceItem>
            {
                new InvoiceItem { ItemName = "Product T", Quantity = 1, UnitPrice = 450.25m, TotalPrice = 450.25m },
                new InvoiceItem { ItemName = "Product U", Quantity = 3, UnitPrice = 140.00m, TotalPrice = 420.00m },
                new InvoiceItem { ItemName = "Product V", Quantity = 2, UnitPrice = 100.00m, TotalPrice = 200.00m }
            }
        },
        new Invoice
        {
            InvoiceNo = 1009,
            InvoiceDate = new DateTime(2023, 5, 7),
            CustomerName = "Nguyễn Đình Tuyên",
            TotalAmount = 825.90m,
            InvoiceItems = new List<InvoiceItem>
            {
                new InvoiceItem { ItemName = "Product W", Quantity = 2, UnitPrice = 200.25m, TotalPrice = 400.50m },
                new InvoiceItem { ItemName = "Product X", Quantity = 1, UnitPrice = 425.50m, TotalPrice = 425.50m }
            }
        },
        new Invoice
        {
            InvoiceNo = 1010,
            InvoiceDate = new DateTime(2023, 5, 10),
            CustomerName = "Hoàng Dược Sư",
            TotalAmount = 550.40m,
            InvoiceItems = new List<InvoiceItem>
            {
                new InvoiceItem { ItemName = "Product Y", Quantity = 3, UnitPrice = 100.00m, TotalPrice = 300.00m },
                new InvoiceItem { ItemName = "Product Z", Quantity = 2, UnitPrice = 75.20m, TotalPrice = 150.40m }
            }
        }
    };

            return invoices;
        }


        public DataSet GetSampleDataSet()
        {
            DataSet dataSet = new DataSet();

            DataTable masterTable = new DataTable("Invoice");
            masterTable.Columns.Add("InvoiceNo", typeof(int));
            masterTable.Columns.Add("InvoiceDate", typeof(DateTime));
            masterTable.Columns.Add("CustomerName", typeof(string));
            masterTable.Columns.Add("TotalAmount", typeof(decimal));
            dataSet.Tables.Add(masterTable);

            DataTable detailTable = new DataTable("InvoiceItem");
            detailTable.Columns.Add("InvoiceNo", typeof(int));
            detailTable.Columns.Add("ItemName", typeof(string));
            detailTable.Columns.Add("Quantity", typeof(int));
            detailTable.Columns.Add("UnitPrice", typeof(decimal));
            detailTable.Columns.Add("TotalPrice", typeof(decimal));
            dataSet.Tables.Add(detailTable);

            dataSet.Relations.Add("Invoice_InvoiceItem", masterTable.Columns["InvoiceNo"], detailTable.Columns["InvoiceNo"]);

            List<Invoice> invoices = GetSampleData();
            foreach (Invoice invoice in invoices)
            {
                DataRow masterRow = masterTable.NewRow();
                masterRow["InvoiceNo"] = invoice.InvoiceNo;
                masterRow["InvoiceDate"] = invoice.InvoiceDate;
                masterRow["CustomerName"] = invoice.CustomerName;
                masterRow["TotalAmount"] = invoice.TotalAmount;
                masterTable.Rows.Add(masterRow);

                foreach (InvoiceItem item in invoice.InvoiceItems)
                {
                    DataRow detailRow = detailTable.NewRow();
                    detailRow["InvoiceNo"] = invoice.InvoiceNo;
                    detailRow["ItemName"] = item.ItemName;
                    detailRow["Quantity"] = item.Quantity;
                    detailRow["UnitPrice"] = item.UnitPrice;
                    detailRow["TotalPrice"] = item.TotalPrice;
                    detailTable.Rows.Add(detailRow);
                }
            }

            return dataSet;
        }


        private void simpleButton1_Click(object sender, EventArgs e)
        {

            var invoices = GetSampleData();

            var report = new rptInvoice();

            report.DataSource = invoices;

            var printTool = new DevExpress.XtraReports.UI.ReportPrintTool(report);

            printTool.ShowPreviewDialog();
        }

        private void simpleButton2_Click(object sender, EventArgs e)
        {

            var invoices = GetSampleDataSet();

            var report = new rptInvoiceDataSet();

            report.DataSource = invoices;

            var printTool = new DevExpress.XtraReports.UI.ReportPrintTool(report);

            printTool.ShowPreviewDialog();
        }
    }



    public class Invoice
    {
        public int InvoiceNo { get; set; }
        public DateTime InvoiceDate { get; set; }
        public string CustomerName { get; set; }
        public decimal TotalAmount { get; set; }
        public List<InvoiceItem> InvoiceItems { get; set; }
    }

    public class InvoiceItem
    {
        public string ItemName { get; set; }
        public int Quantity { get; set; }
        public decimal UnitPrice { get; set; }
        public decimal TotalPrice { get; set; }
    }
}


DOWNLOAD FULL SOURCE CODE.

DOWNLOAD SOURCE CODE


on Thứ Ba, 23 tháng 4, 2024 | , , , | A comment?

[DEVEXPRESS] How to using HTML and CSS code viewer

Xin chào các bạn, bài viết hôm nay mình tiếp tục chia sẻ các bạn cách sử dụng HTMLCodeViewer và CSSCodeViewer trên Devexpress Winform. [DEVEXPRESS] Hướng dẫn sử dụng HTML and CSS Code Viewer trên Winform Hai control này trên Devexpress mặc định không có hiển thị ở thanh ToolBox của Visual Studio.


Nên các bạn cần viết một vào dòng code để hiện thị nó lên và gắn vào Panel control. Giao diện demo ứng dụng:

Các bạn có thể xem video hướng dẫn từng bước thực hiện:



Source code C#:
using DevExpress.XtraEditors.Internal;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

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

        private void Form1_Load(object sender, EventArgs e)
        {
            var htmlCodeEditor = new HtmlCodeViewer();
            htmlCodeEditor.ReadOnly = false;
            htmlCodeEditor.Dock = DockStyle.Fill;
            htmlCodeEditor.AllowCodeFolding = DevExpress.Utils.DefaultBoolean.True;
            htmlCodeEditor.ShowIndentGuides = DevExpress.Utils.DefaultBoolean.True;
            htmlCodeEditor.ShowLineNumbers = DevExpress.Utils.DefaultBoolean.True;
            htmlCodeEditor.ScrollBars = ScrollBars.Both;

            // add control to panel
            panelHTMLEditor.Controls.Add(htmlCodeEditor);

            var cssCodeEditor = new CssCodeViewer();
            cssCodeEditor.ReadOnly = false;
            cssCodeEditor.Dock = DockStyle.Fill;
            cssCodeEditor.AllowCodeFolding = DevExpress.Utils.DefaultBoolean.True;
            cssCodeEditor.ShowIndentGuides = DevExpress.Utils.DefaultBoolean.True;
            cssCodeEditor.ShowLineNumbers = DevExpress.Utils.DefaultBoolean.True;
            cssCodeEditor.ScrollBars = ScrollBars.Both;
            // press Ctrol + Alt + . => multi select in visual studio
            // add control to panel
            panelCSSEditor.Controls.Add(cssCodeEditor);
        }
    }
}

Chúc mọi người thành công với thủ thuật trên.

DOWNLOAD SOURCE CODE


PASSWORD UNZIP: HUNG.PRO.VN

on Chủ Nhật, 14 tháng 4, 2024 | , , , , | A comment?