(四十九)c#Winform自定义控件-下拉框(表格)

前提

入行已经7,8年了,一直想做一套漂亮点的自定义控件,于是就有了本系列文章。

GitHub:https://github.com/kwwwvagaa/NetWinformControl

码云:https://gitee.com/kwwwvagaa/net_winform_custom_control.git

如果觉得写的还行,请点个 star 支持一下吧

欢迎前来交流探讨: 企鹅群568015492 企鹅群568015492

麻烦博客下方点个【推荐】,谢谢

NuGet

Install-Package HZH_Controls

目录

https://blog.csdn.net/kwwwvagaa/article/details/100586547

用处及效果

复制代码

 1   List<DataGridViewColumnEntity> lstCulumns = new List<DataGridViewColumnEntity>();
 2             lstCulumns.Add(new DataGridViewColumnEntity() { DataField = "ID", HeadText = "编号", Width = 70, WidthType = SizeType.Absolute });
 3             lstCulumns.Add(new DataGridViewColumnEntity() { DataField = "Name", HeadText = "姓名", Width = 100, WidthType = SizeType.Absolute });
 4             lstCulumns.Add(new DataGridViewColumnEntity() { DataField = "Age", HeadText = "年龄", Width = 100, WidthType = SizeType.Absolute });
 5             lstCulumns.Add(new DataGridViewColumnEntity() { DataField = "Birthday", HeadText = "生日", Width = 120, WidthType = SizeType.Absolute, Format = (a) => { return ((DateTime)a).ToString("yyyy-MM-dd"); } });
 6             lstCulumns.Add(new DataGridViewColumnEntity() { DataField = "Sex", HeadText = "性别", Width = 100, WidthType = SizeType.Absolute, Format = (a) => { return ((int)a) == 0 ? "女" : "男"; } });
 7             this.ucComboxGrid1.GridColumns = lstCulumns;
 8             List<object> lstSourceGrid = new List<object>();
 9             for (int i = 0; i < 100; i++)
10             {
11                 TestModel model = new TestModel()
12                 {
13                     ID = i.ToString(),
14                     Age = 3 * i,
15                     Name = "姓名——" + i,
16                     Birthday = DateTime.Now.AddYears(-10),
17                     Sex = i % 2
18                 };
19                 lstSourceGrid.Add(model);
20             }
21             this.ucComboxGrid1.GridDataSource = lstSourceGrid;

复制代码

 

准备工作

此控件继承自UCCombox,并且需要表格控件UCDataGridView,如果不了解请移步查看

(三十五)c#Winform自定义控件-下拉框

(三十二)c#Winform自定义控件-表格

如果你想显示树形结构,请移步查看

(四十七)c#Winform自定义控件-树表格(treeGrid)

开始

我们首先需要一个弹出的面板,那么我们先添加一个用户控件UCComboxGridPanel,在这个用户控件上添加一个文本框进行搜索,添加一个表格展示数据

一些属性

复制代码

 1  [Description("项点击事件"), Category("自定义")]
 2         public event DataGridViewEventHandler ItemClick;
 3         private Type m_rowType = typeof(UCDataGridViewRow);
 4 
 5         public Type RowType
 6         {
 7             get { return m_rowType; }
 8             set
 9             {
10                 m_rowType = value;
11                 this.ucDataGridView1.RowType = m_rowType;
12             }
13         }
14 
15         private List<DataGridViewColumnEntity> m_columns = null;
16 
17         public List<DataGridViewColumnEntity> Columns
18         {
19             get { return m_columns; }
20             set
21             {
22                 m_columns = value;
23                 this.ucDataGridView1.Columns = value;
24             }
25         }
26         private List<object> m_dataSource = null;
27 
28         public List<object> DataSource
29         {
30             get { return m_dataSource; }
31             set { m_dataSource = value; }
32         }
33 
34         private string strLastSearchText = string.Empty;
35         UCPagerControl m_page = new UCPagerControl();

复制代码

一些事件,处理数据绑定

复制代码

 1  void ucDataGridView1_ItemClick(object sender, DataGridViewEventArgs e)
 2         {
 3             if (ItemClick != null)
 4             {
 5                 ItemClick((sender as IDataGridViewRow).DataSource, null);
 6             }
 7         }
 8 
 9         void txtInput_TextChanged(object sender, EventArgs e)
10         {
11             timer1.Enabled = false;
12             timer1.Enabled = true;
13         }
14 
15         private void UCComboxGridPanel_Load(object sender, EventArgs e)
16         {
17             m_page.DataSource = m_dataSource;
18             this.ucDataGridView1.DataSource = m_page.GetCurrentSource();
19         }
20 
21         private void timer1_Tick(object sender, EventArgs e)
22         {
23             if (strLastSearchText == txtSearch.InputText)
24             {
25                 timer1.Enabled = false;
26             }
27             else
28             {
29                 strLastSearchText = txtSearch.InputText;
30                 Search(txtSearch.InputText);
31             }
32         }
33 
34         private void Search(string strText)
35         {
36             m_page.StartIndex = 0;
37             if (!string.IsNullOrEmpty(strText))
38             {
39                 strText = strText.ToLower();
40                 List<object> lst = m_dataSource.FindAll(p => m_columns.Any(c => (c.Format == null ? (p.GetType().GetProperty(c.DataField).GetValue(p, null).ToStringExt()) : c.Format(p.GetType().GetProperty(c.DataField).GetValue(p, null))).ToLower().Contains(strText)));
41                 m_page.DataSource = lst;
42             }
43             else
44             {
45                 m_page.DataSource = m_dataSource;
46             }
47             m_page.Reload();
48         }

复制代码

完整代码

 View Code

 View Code

以上,弹出面板完成,下面就是下拉控件了

添加一个用户控件UCComboxGrid,继承UCCombox

一些属性

复制代码

 1  private Type m_rowType = typeof(UCDataGridViewRow);
 2 
 3         [Description("表格行类型"), Category("自定义")]
 4         public Type GridRowType
 5         {
 6             get { return m_rowType; }
 7             set
 8             {
 9                 m_rowType = value;
10             }
11         }
12         int intWidth = 0;
13 
14         private List<DataGridViewColumnEntity> m_columns = null;
15 
16         [Description("表格列"), Category("自定义")]
17         public List<DataGridViewColumnEntity> GridColumns
18         {
19             get { return m_columns; }
20             set
21             {
22                 m_columns = value;
23                 if (value != null)
24                     intWidth = value.Sum(p => p.WidthType == SizeType.Absolute ? p.Width : (p.Width < 80 ? 80 : p.Width));
25             }
26         }
27         private List<object> m_dataSource = null;
28 
29         [Description("表格数据源"), Category("自定义")]
30         public List<object> GridDataSource
31         {
32             get { return m_dataSource; }
33             set { m_dataSource = value; }
34         }
35 
36         private string m_textField;
37 
38         [Description("显示值字段名称"), Category("自定义")]
39         public string TextField
40         {
41             get { return m_textField; }
42             set
43             {
44                 m_textField = value;
45                 SetText();
46             }
47         }
48         [Obsolete("不再可用的属性")]
49         [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)]
50         private new ComboBoxStyle BoxStyle
51         {
52             get;
53             set;
54         }
55         private object selectSource = null;
56 
57         [Description("选中的数据源"), Category("自定义")]
58         public object SelectSource
59         {
60             get { return selectSource; }
61             set
62             {
63                 selectSource = value;
64                 SetText();
65                 if (SelectedChangedEvent != null)
66                 {
67                     SelectedChangedEvent(value, null);
68                 }
69             }
70         }
71 
72  [Description("选中数据源改变事件"), Category("自定义")]
73         public new event EventHandler SelectedChangedEvent;

复制代码

重写点击事件来处理弹出

复制代码

 1  protected override void click_MouseDown(object sender, MouseEventArgs e)
 2         {
 3             if (m_columns == null || m_columns.Count <= 0)
 4                 return;
 5             if (m_ucPanel == null)
 6             {
 7                 var p = this.Parent.PointToScreen(this.Location);
 8                 int intScreenHeight = Screen.PrimaryScreen.Bounds.Height;
 9                 int intHeight = Math.Max(p.Y, intScreenHeight - p.Y - this.Height);
10                 intHeight -= 100;
11                 m_ucPanel = new UCComboxGridPanel();
12                 m_ucPanel.ItemClick += m_ucPanel_ItemClick;
13                 m_ucPanel.Height = intHeight;
14                 m_ucPanel.Width = intWidth;
15                 m_ucPanel.Columns = m_columns;
16                 m_ucPanel.RowType = m_rowType;
17                 if (m_dataSource != null && m_dataSource.Count > 0)
18                 {
19                     int _intHeight = Math.Min(110 + m_dataSource.Count * 36, m_ucPanel.Height);
20                     m_ucPanel.Height = _intHeight;
21                 }
22             }
23             m_ucPanel.DataSource = m_dataSource;
24             if (_frmAnchor == null || _frmAnchor.IsDisposed || _frmAnchor.Visible == false)
25             {
26                 _frmAnchor = new Forms.FrmAnchor(this, m_ucPanel);
27                 _frmAnchor.Show(this.FindForm());
28             }
29 
30         }
31 
32         void m_ucPanel_ItemClick(object sender, DataGridViewEventArgs e)
33         {
34             _frmAnchor.Hide();
35             SelectSource = sender;
36         }
37 
38         private void SetText()
39         {
40             if (!string.IsNullOrEmpty(m_textField) && selectSource != null)
41             {
42                 var pro = selectSource.GetType().GetProperty(m_textField);
43                 if (pro != null)
44                 {
45                     TextValue = pro.GetValue(selectSource, null).ToStringExt();
46                 }
47             }
48         }

复制代码

完整代码

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using HZH_Controls.Controls;

namespace HZH_Controls.Controls.ComboBox
{
    public partial class UCComboxGrid : UCCombox
    {

        private Type m_rowType = typeof(UCDataGridViewRow);

        [Description("表格行类型"), Category("自定义")]
        public Type GridRowType
        {
            get { return m_rowType; }
            set
            {
                m_rowType = value;
            }
        }
        int intWidth = 0;

        private List<DataGridViewColumnEntity> m_columns = null;

        [Description("表格列"), Category("自定义")]
        public List<DataGridViewColumnEntity> GridColumns
        {
            get { return m_columns; }
            set
            {
                m_columns = value;
                if (value != null)
                    intWidth = value.Sum(p => p.WidthType == SizeType.Absolute ? p.Width : (p.Width < 80 ? 80 : p.Width));
            }
        }
        private List<object> m_dataSource = null;

        [Description("表格数据源"), Category("自定义")]
        public List<object> GridDataSource
        {
            get { return m_dataSource; }
            set { m_dataSource = value; }
        }

        private string m_textField;

        [Description("显示值字段名称"), Category("自定义")]
        public string TextField
        {
            get { return m_textField; }
            set
            {
                m_textField = value;
                SetText();
            }
        }
        [Obsolete("不再可用的属性")]
        [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)]
        private new ComboBoxStyle BoxStyle
        {
            get;
            set;
        }
        private object selectSource = null;

        [Description("选中的数据源"), Category("自定义")]
        public object SelectSource
        {
            get { return selectSource; }
            set
            {
                selectSource = value;
                SetText();
                if (SelectedChangedEvent != null)
                {
                    SelectedChangedEvent(value, null);
                }
            }
        }

      

        [Description("选中数据源改变事件"), Category("自定义")]
        public new event EventHandler SelectedChangedEvent;
        public UCComboxGrid()
        {
            InitializeComponent();
        }
        UCComboxGridPanel m_ucPanel = null;
        Forms.FrmAnchor _frmAnchor;
        protected override void click_MouseDown(object sender, MouseEventArgs e)
        {
            if (m_columns == null || m_columns.Count <= 0)
                return;
            if (m_ucPanel == null)
            {
                var p = this.Parent.PointToScreen(this.Location);
                int intScreenHeight = Screen.PrimaryScreen.Bounds.Height;
                int intHeight = Math.Max(p.Y, intScreenHeight - p.Y - this.Height);
                intHeight -= 100;
                m_ucPanel = new UCComboxGridPanel();
                m_ucPanel.ItemClick += m_ucPanel_ItemClick;
                m_ucPanel.Height = intHeight;
                m_ucPanel.Width = intWidth;
                m_ucPanel.Columns = m_columns;
                m_ucPanel.RowType = m_rowType;
                if (m_dataSource != null && m_dataSource.Count > 0)
                {
                    int _intHeight = Math.Min(110 + m_dataSource.Count * 36, m_ucPanel.Height);
                    m_ucPanel.Height = _intHeight;
                }
            }
            m_ucPanel.DataSource = m_dataSource;
            if (_frmAnchor == null || _frmAnchor.IsDisposed || _frmAnchor.Visible == false)
            {
                _frmAnchor = new Forms.FrmAnchor(this, m_ucPanel);
                _frmAnchor.Show(this.FindForm());
            }

        }

        void m_ucPanel_ItemClick(object sender, DataGridViewEventArgs e)
        {
            _frmAnchor.Hide();
            SelectSource = sender;
        }

        private void SetText()
        {
            if (!string.IsNullOrEmpty(m_textField) && selectSource != null)
            {
                var pro = selectSource.GetType().GetProperty(m_textField);
                if (pro != null)
                {
                    TextValue = pro.GetValue(selectSource, null).ToStringExt();
                }
            }
        }
    }
}
namespace HZH_Controls.Controls.ComboBox
{
    partial class UCComboxGrid
    {
        /// <summary> 
        /// 必需的设计器变量。
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary> 
        /// 清理所有正在使用的资源。
        /// </summary>
        /// <param name="disposing">如果应释放托管资源,为 true;否则为 false。</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region 组件设计器生成的代码

        /// <summary> 
        /// 设计器支持所需的方法 - 不要
        /// 使用代码编辑器修改此方法的内容。
        /// </summary>
        private void InitializeComponent()
        {
            this.SuspendLayout();
            // 
            // txtInput
            // 
            this.txtInput.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(240)))), ((int)(((byte)(240)))), ((int)(((byte)(240)))));
            // 
            // UCComboxGrid
            // 
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.None;
            this.BackColor = System.Drawing.Color.Transparent;
            this.BoxStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
            this.FillColor = System.Drawing.Color.FromArgb(((int)(((byte)(240)))), ((int)(((byte)(240)))), ((int)(((byte)(240)))));
            this.Name = "UCComboxGrid";
            this.RectColor = System.Drawing.Color.FromArgb(((int)(((byte)(240)))), ((int)(((byte)(240)))), ((int)(((byte)(240)))));
            this.ResumeLayout(false);
            this.PerformLayout();

        }

        #endregion

    }
}

以上就是全部东西了

最后的话

如果你喜欢的话,请到 https://gitee.com/kwwwvagaa/net_winform_custom_control 点个星星吧

  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值