使用自定义数据源时如何隐藏DataGridView的列?

发布于 2024-11-28 04:12:24 字数 967 浏览 3 评论 0原文

我有一个 c# 中的小应用程序,它有一个 DataGridView,可以使用以下方式填充:

grid.DataSource = MyDatasource array;

MyClass 保存列的结构,它看起来像这样:

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 填充了正确的数据,但现在我想隐藏 column2。我尝试在列声明上方添加 [Browsable(false)] ,这将隐藏它,但我还需要从代码访问列值,当我使用 [Browsable(false) 时] 并尝试读取内容,就像该列不存在时一样。如果我不使用它,我可以毫无问题地读取该列,但它在 DataGridView 中可见。

如何隐藏该列但仍然能够从代码中读取其内容?

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

grid.DataSource = MyDatasource array;

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;
        }
    }
}

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.

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(10

困倦 2024-12-05 04:12:24

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

例如,我有一个类,它具有用于公司徽标的 Image 属性的 NHibernate 代理。如果我访问该属性(例如,通过调用其 ToString 方法以在 DataGridView 中显示该属性),它将从 SQL 服务器下载图像。如果我有一个 Company 对象列表并将其用作 DataGridView 的数据源,那么(我怀疑)它会在我隐藏该列之前下载所有徽标。

为了防止这种情况,我在图像属性上使用了自定义属性

 [System.ComponentModel.Browsable(false)]

,以便 DataGridView 忽略该属性(不创建列,也不调用 ToString 方法)。

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

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

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.

To prevent this, I used the custom attribute

 [System.ComponentModel.Browsable(false)]

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;}
日暮斜阳 2024-12-05 04:12:24

您必须隐藏网格视图控件中的列,而不是数据源中的列。将其隐藏在数据源中,它根本不会呈现到网格视图,因此您将无法访问网格视图中的值。按照您建议的方式执行此操作,您必须通过数据源而不是网格视图访问列值。

要隐藏网格视图控件上的列,您可以使用如下代码:

dataGridView1.Columns[0].Visible = false;

要从数据源访问该列,您可以尝试如下操作:

object colValue = ((DataTable)dataGridView.DataSource).Rows[dataSetIndex]["ColumnName"];

You have to hide the column at the grid view control rather than at the data source. Hiding it at the data source it will not render to the grid view at all, therefore you won't be able to access the value in the grid view. Doing it the way you're suggesting, you would have to access the column value through the data source as opposed to the grid view.

To hide the column on the grid view control, you can use code like this:

dataGridView1.Columns[0].Visible = false;

To access the column from the data source, you could try something like this:

object colValue = ((DataTable)dataGridView.DataSource).Rows[dataSetIndex]["ColumnName"];
成熟稳重的好男人 2024-12-05 04:12:24

我注意到,如果以编程方式使用,如果在 panel1.Controls.Add(dataGridView); 然后 dataGridView.Columns[" 之前使用,它会呈现不完整(整个表单根本不会“绘制”任何内容) ID"].Visible = false; 将破坏整个表单并将其设为空白,因此要避免设置此 AFTER EG:

 panel1.Controls.Add(dataGridView);
 dataGridView.Columns["ID"].Visible = false; 
 //works

 dataGridView.Columns["ID"].Visible = false; 
 panel1.Controls.Add(dataGridView);
 //fails miserably

I have noticed that if utilised progrmmatically it renders incomplete (entire form simply doesn't "paint" anything) if used before panel1.Controls.Add(dataGridView); then dataGridView.Columns["ID"].Visible = false; will break the entire form and make it blank, so to get round that set this AFTER EG:

 panel1.Controls.Add(dataGridView);
 dataGridView.Columns["ID"].Visible = false; 
 //works

 dataGridView.Columns["ID"].Visible = false; 
 panel1.Controls.Add(dataGridView);
 //fails miserably
情深已缘浅 2024-12-05 04:12:24

我不确定是否为时已晚,但问题是,如果在运行时绑定,则无法在设计模式中设置列。因此,如果在运行时绑定,请继续从设计模式中删除列,然后务实地做事,

例如..

     if (dt.Rows.Count > 0)
    {
        dataGridViewProjects.DataSource = dt;
        dataGridViewProjects.Columns["Title"].Width = 300;
        dataGridViewProjects.Columns["ID"].Visible = false;
    }

I"m not sure if its too late, but the problem is that, you cannot set the columns in design mode if you are binding at runtime. So if you are binding at runtime, go ahead and remove the columns from the design mode and do it pragmatically

ex..

     if (dt.Rows.Count > 0)
    {
        dataGridViewProjects.DataSource = dt;
        dataGridViewProjects.Columns["Title"].Width = 300;
        dataGridViewProjects.Columns["ID"].Visible = false;
    }
淡写薰衣草的香 2024-12-05 04:12:24

设置该特定列的 Visible 属性 = false

dataGridView[ColumnName or Index].Visible = false;

编辑
抱歉错过了 Columns 属性
dataGridView.Columns[ColumnName 或 Index].Visible = false;

Set that particular column's Visible property = false

dataGridView[ColumnName or Index].Visible = false;

Edit
sorry missed the Columns Property
dataGridView.Columns[ColumnName or Index].Visible = false;

北凤男飞 2024-12-05 04:12:24

我遇到了同样的问题

这是可能适合您的解决方案。这对我有用

    GridView1.DataBind();
if (GridView1.Columns.Count > 0)
    GridView1.Columns[0].Visible = false;
else
{
    GridView1.HeaderRow.Cells[0].Visible = false;
    foreach (GridViewRow gvr in GridView1.Rows)
    {
        gvr.Cells[0].Visible = false;
    }
}

I had the same problem

Here is the Solution that might work for you. It worked for me

    GridView1.DataBind();
if (GridView1.Columns.Count > 0)
    GridView1.Columns[0].Visible = false;
else
{
    GridView1.HeaderRow.Cells[0].Visible = false;
    foreach (GridViewRow gvr in GridView1.Rows)
    {
        gvr.Cells[0].Visible = false;
    }
}
心奴独伤 2024-12-05 04:12:24

只需设置DataGridView.AutoGenerateColumns = false;

您需要单击右上角的箭头(在 datagridview 中)来添加列,并且在 DataPropertyName 中,您需要将属性名称放入类中。

然后,在 datagridview 中定义列后,您可以设置 datagridview.datasource = myClassViewModel

Just set DataGridView.AutoGenerateColumns = false;

You need click on the arrow on top right corner (in datagridview) to add columns, and in DataPropertyName you need to put a name of your property in your class.

Then, after you defined your columns in datagridview, you can set datagridview.datasource = myClassViewModel.

梦与时光遇 2024-12-05 04:12:24

MyDataGridView.RowHeadersVisible = False;
在绑定和重命名每个列标题并设置列宽度之前。
为了在我搜索时帮助我衰退的记忆,因为我会搜索......这是肯定的;-)

MyDataGridView.RowHeadersVisible = False;
Before binding and rename each columns header and set columns width.
To help my failing memory when I search, because I will search ... that's for sure ;-)

歌入人心 2024-12-05 04:12:24

如果您想使用 BrowsableAttribute,那么您可以在运行时在模型上查找它并相应地隐藏该列:

private void Form_Load(object sender, EventArgs e)
{
    //add this line after your DataGridView initialization
    HideColumns<MyModel>(myDvg);
}

private void HideColumns<T>(DataGridView dvg)
{
    var type = typeof(T);
    foreach (var column in dvg.Columns.Cast<DataGridViewColumn>())
        column.Visible = IsBrowsable(type.GetProperty(column.Name));
}

private bool IsBrowsable(PropertyInfo propertyInfo)
{
    var attribute = propertyInfo.GetCustomAttributes(true).FirstOrDefault(att => att.GetType() == typeof(BrowsableAttribute));
    return attribute == null || (attribute as BrowsableAttribute).Browsable;
}

If you want to use the BrowsableAttribute, then you can look for it at runtime on the model and hide the column accordingly:

private void Form_Load(object sender, EventArgs e)
{
    //add this line after your DataGridView initialization
    HideColumns<MyModel>(myDvg);
}

private void HideColumns<T>(DataGridView dvg)
{
    var type = typeof(T);
    foreach (var column in dvg.Columns.Cast<DataGridViewColumn>())
        column.Visible = IsBrowsable(type.GetProperty(column.Name));
}

private bool IsBrowsable(PropertyInfo propertyInfo)
{
    var attribute = propertyInfo.GetCustomAttributes(true).FirstOrDefault(att => att.GetType() == typeof(BrowsableAttribute));
    return attribute == null || (attribute as BrowsableAttribute).Browsable;
}
没有你我更好 2024-12-05 04:12:24

尝试遵循:

DataGridView1.Columns["YourColumnName"].Visible = false;

Try follow:

DataGridView1.Columns["YourColumnName"].Visible = false;
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文