- 精品下载 | 实用查询 | 词典查询 | 桌面壁纸 | 网址 | 笑话 | FLASH频道 | 天气文章资讯 | 站长工具 | 证件办理 | 闪字生成 | 广告代码 | 在线手册 | 有问必答
您现在的位置: 蓝派网 >> 文章中心 >> 网络编程 >> .NET >> .NetFramework >> 正文
站内文章搜索:           

VS2005 DataGridView 控件设置自定义列方法

作者:佚名    文章来源:网络转载    更新时间 :2007-11-25 13:34:56

自从使用VS.NET后,就很少写WinForm程序了,都以WebForm为主, 但毕竟是WinForm出身,VS.NET有这么强大的功能如果不实践实践岂不可惜,所以经常自己找点题目操练操练,上星期操练时,看有文章说VS2005 DataGridView 控件比VS2003的DataGrid控件还好用,还说是MS想用DataGridView取代DataGrid,那当然也想试试了,使用时才发现DataGridView 控件没有想像中的那么好用,我在使用DataGrid习惯了自定义列的功能,但在DataGridView却发现自定义列功能不知道怎么用,比方说DataGridView绑定了Northwind中的Products表(SELECT * FROM Products),SQL语句定义有多少列,DataGridView就自动绑定了多少列(如图所示)

如果我只想绑定ProductID和ProductName字段却不知道怎么定义,查看MSDN发现有两种方法1.设置Column的Collection属性;2.DataGridView.Columns的Add或AddRange方法,但通过以上两种方法我不管怎么处理都是ProductID和ProductName两列再加上Products的所有列,BaiDu和Google后发现WinForm的DataGridView特别少,而且也没有什么方案解决问题,研究半天也没结果,特别郁闷,今天想再研究一下,发现DataGridView.Columns还有一个Clear方法,突发奇想:把列都清除再添加列是否可行,一试就发现果然可行(如图所示)

简单演示代码:

System.Windows.Forms.DataGridViewTextBoxColumn ProductID = new DataGridViewTextBoxColumn();
                ProductID.DataPropertyName = "ProductID";
                ProductID.HeaderText = "产品ID";
                ProductID.Name = "ProductID";
                ProductID.Resizable = System.Windows.Forms.DataGridViewTriState.True;

                System.Windows.Forms.DataGridViewTextBoxColumn ProductName = new DataGridViewTextBoxColumn();
                ProductName.DataPropertyName = "ProductName";
                ProductName.HeaderText = "产品名称";
                ProductName.Name = "ProductName";
                ProductName.Resizable = System.Windows.Forms.DataGridViewTriState.True;

                DataSet ds = (...获取数据代码略) 


                if (ds != null)
                {
                     dataGridView1.DataSource = ds.Tables["Products"].DefaultView; 
                    dataGridView1.Columns.Clear();//一定要先绑定数据后再清除列,不然没有效果
                    dataGridView1.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] { ProductID });
                    dataGridView1.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] { ProductName });
                }

 

 
【相关文章:】
没有相关文章

发表评论】【打印此文】【关闭窗口】【点击数:
★好玩的休闲小游戏★
网友评论:
数据载入中,请稍后……