惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

W
WeLiveSecurity
The GitHub Blog
The GitHub Blog
Engineering at Meta
Engineering at Meta
Microsoft Azure Blog
Microsoft Azure Blog
The Register - Security
The Register - Security
Stack Overflow Blog
Stack Overflow Blog
博客园 - 三生石上(FineUI控件)
T
Threat Research - Cisco Blogs
S
SegmentFault 最新的问题
V2EX - 技术
V2EX - 技术
Hacker News: Ask HN
Hacker News: Ask HN
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
P
Proofpoint News Feed
J
Java Code Geeks
Microsoft Security Blog
Microsoft Security Blog
M
MIT News - Artificial intelligence
AI
AI
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
P
Proofpoint News Feed
Hacker News - Newest:
Hacker News - Newest: "LLM"
B
Blog
N
News and Events Feed by Topic
N
News | PayPal Newsroom
Google DeepMind News
Google DeepMind News
酷 壳 – CoolShell
酷 壳 – CoolShell
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
WordPress大学
WordPress大学
C
Cybersecurity and Infrastructure Security Agency CISA
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
博客园 - 【当耐特】
U
Unit 42
腾讯CDC
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
The Cloudflare Blog
H
Help Net Security
Recent Announcements
Recent Announcements
P
Privacy & Cybersecurity Law Blog
IT之家
IT之家
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
Security Archives - TechRepublic
Security Archives - TechRepublic
L
LINUX DO - 热门话题
Martin Fowler
Martin Fowler
MongoDB | Blog
MongoDB | Blog
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
H
Heimdal Security Blog
博客园 - 聂微东
S
Securelist
大猫的无限游戏
大猫的无限游戏
Cloudbric
Cloudbric
Cisco Talos Blog
Cisco Talos Blog

博客园 - magicdlf

[HIMCM暑期班]第4课: 扑克牌问题 [HIMCM暑期班]第3课:一个博弈问题 [HIMCM暑期班]第2课:建模 [HIMCM暑期班]第1课:概述 [C#]ASP.NET MVC 3 在线学习资料 [HIMCM]Consortium可以免费下载了! [C#]在Windows Service中使用ThreadPool [HIMCM]MathType小练习 SRM 518 解题报告 SRM 522 解题报告 SRM 521 解题报告 [原创]简易版Socket聊天室 附源码 再谈C#扫雷 C#实现扫雷出炉 如何通过P/Invoke返回Struct和String Array 计算文件的散列值 zz .NET抽象工厂模式 from cnblogs 清空VSTFS cache 如何在VSTFS中设置email notification
[C#]DataGridView中使用数据绑定Enum类型
magicdlf · 2013-04-29 · via 博客园 - magicdlf

在Windows Application中,常常会出现使用DataGridView + data binding来维护一组相似数据的例子,例如:

对于常规类型的变量来说,只需要简单地设置DataGridView的DataSource就可以实现绑定了:

例如我有一个ColumnConfig的类

    public enum ConfigMode
    {
        Exact,
        Similar,
        Ignore
    }

    [XmlType("ColumnConfig")]
    public class ColumnConfig : INotifyPropertyChanged
    {
        [XmlElement]
        public string ColumnName
        {
            get;
            set;
        }

        [XmlElement]
        public string Regex
        {
            get;
            set;
        }
        [XmlElement]
        public bool IsNumber
        {
            get;
            set;
        }
        [XmlElement]
        public bool IsOutput
        {
            get;
            set;
        }

        public ConfigMode ConfigMode
        {
            get;
            set;
        }

        public ColumnConfig()
        {
            this.ColumnName = null;
            IsOutput = true;
            Regex = null;
            IsNumber = false;
            ConfigMode = ConfigMode.Ignore;
        }

        public ColumnConfig(string columnName)
        {
            this.ColumnName = columnName;
            IsOutput = true;
            Regex = null;
            IsNumber = false;
            ConfigMode = ConfigMode.Ignore;
        }

        public event PropertyChangedEventHandler PropertyChanged;
    }

在绑定时只需要这样一小段代码:

                    configs = new BindingList<ColumnConfig>();
                    foreach (DataColumn col in dataTable.Columns)
                    {
                        DataGridViewRow dgvr = new DataGridViewRow();
                        ColumnConfig config = new ColumnConfig(col.ColumnName.ToString());
                        configs.Add(config);
                    }
                    grid_ColumnConfigs.DataSource = configs;

意思就是,只要将DataGridView的DataSource绑定到BindingList<MyClass>上就可以完成这项任务。

但是当我希望用下拉菜单来表示ColumnConfig中的枚举类型ConfigMode的时候,我们还需要一些额外的工作:

在Initialize DataGridView之前,你需要做:

            DataGridViewComboBoxColumn myCombo = new DataGridViewComboBoxColumn();
            myCombo.DataSource = new ConfigMode[] { ConfigMode.Exact, ConfigMode.Similar, ConfigMode.Ignore };
            myCombo.HeaderText = "ConfigMode";
            myCombo.Name = "ConfigMode";
            myCombo.ValueType = typeof(ConfigMode);
            myCombo.DataPropertyName = "ConfigMode";
            grid_ColumnConfigs.Columns.Add(myCombo);
            this.grid_ColumnConfigs.DataSource = jobInfo.ColumnConfigs;

注意:

1. myCombo.DataSource指的是每一行的下拉菜单中,显示给用户的选项。ValueType很关键,一定要指定是枚举的类型才能实现DataBinding。DataPropertyName就是在ColumnConfig中哪一些属性被绑定到这里。

2. 我在网上见到有人这么写: myCombo.DataSource = Enum.GetNames(typeof(ConfigMode)); 这个方法的确可以让下拉菜单也显示所有的选项,但是它们是字符串类型的,也就是说没有简单的办法可以让它们变回枚举值!所以你一定会碰到一个叫:“System.Argument.Exception: DataGridViewComboBoxCell value is not valid”的问题。

3. 解决以上问题的方法有很多种,点名批评以下这种:

http://blog.csdn.net/cnjack/article/details/4561376

 //处理掉DataGridViewComboBoxColumn绑定数据源后,再绑定到DataTable中的Column时,提示"System.ArgumentException:DagaGridViewComboBoxCell值无效"的错误
 this.dataGridView1.DataError += delegate(object sender, DataGridViewDataErrorEventArgs e) { };

这种方式只会使出错的弹出窗口不再显示,但是DataBinding是失效的。

4. 拓展一下:如果你不是想绑定到Enum,而是想绑定到一个自己的Class,那么这个方法适合你:

http://stackoverflow.com/questions/1503649/problem-when-adding-combobox-to-datagridview

DataGridViewComboBoxColumn col = new ...
col.DataSource = columnDataSource;
col.DisplayMember = "Name";
col.ValueMember = "Value";
col.DataPropertyName = "Type";

综上,只要设置好ValueType就可以解决好Enum的问题。