如何使用自定义数据源时,隐藏的DataGridView的列? [英] How to hide column of DataGridView when using custom DataSource?

查看:193
本文介绍了如何使用自定义数据源时,隐藏的DataGridView的列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在C#中的小的应用程序,它有一个DataGridView,获取使用填充:

I have a small app in c#, it has a DataGridView that gets filled using:

grid.DataSource = MyDatasource阵列;

MyClass的持有结构,为列,它看起来是这样的:

MyClass hold the structure for the columns, it looks something like this:

class MyDatasource
{
    private string column1;        
    private string column2;

    public MyDatasource(string arg1, string arg2)
    {
        this.column1 = arg1;
        this.column2 = arg2;
    }

    public string column1
    {
        get
        {
            return this.column1;
        }
        set
        {
            this.column1 = value;
        }
    }

    public string column2
    {
        get
        {
            return this.column2;
        }
        set
        {
            this.column1 = value;
        }
    }
}

一切工作正常和DataGridView获取填入正确的数据,但现在我想隐藏的列2。我尝试添加 [可浏览(假)] 上面列声明,将其隐藏,但我也需要访问从code中的列值,而当我使用 [可浏览(假)] 并尝试读取它的行为,如果列不存在类似的内容。如果我不使用它,我可以读取没有问题的列,但它是可见在DataGridView。

Everything works fine and the DataGridView gets populated with the correct data, but now I want to hide the column2. I tried adding [Browsable(false)] above the column declaration, that will hide it, but I also need to access the column value from code, and when I use [Browsable(false)] and try to read the content it acts like if the column doesn't exist. If I don't use it I can read the column without problem but it's visible in the DataGridView.

我怎么能隐藏列,但仍然能够读取code的内容?

How could I hide the column but still be able to read its content from code?

推荐答案

在某些情况下,它可能是一个坏主意,先列添加到DataGridView,然后将其隐藏。

In some cases, it might be a bad idea to first add the column to the DataGridView and then hide it.

我比如有一个具有为公司标志的图像属性的NHibernate的代理类。如果我访问的属性(例如,通过调用其ToString方法显示在一个DataGridView),它会从SQL服务器下载图像。如果我有公司的对象的列表,并使用了作为像在DataGridView的数据源,然后(我怀疑),它会下载所有标识之前,我可以隐藏列。

I for example have a class that has an NHibernate proxy for an Image property for company logos. If I accessed that property (e.g. by calling its ToString method to show that in a DataGridView), it would download the image from the SQL server. If I had a list of Company objects and used that as the dataSource of the DataGridView like that, then (I suspect) it would download ALL the logos BEFORE I could hide the column.

要prevent这一点,我使用了自定义属性

To prevent this, I used the custom attribute

 [System.ComponentModel.Browsable(false)]

上的图像特性,使得在DataGridView忽略属性(不创建列和不调用的ToString方法)。

on the image property, so that the DataGridView ignores the property (doesn't create the column and doesn't call the ToString methods).

 public class Company
 {
     ...
     [System.ComponentModel.Browsable(false)]
     virtual public MyImageClass Logo { get; set;}

这篇关于如何使用自定义数据源时,隐藏的DataGridView的列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆