c#使用数据源隐藏datagridview中的属性

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1152951/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 09:29:19  来源:igfitidea点击:

c# Hide a property in datagridview with datasource

c#attributesdatasource

提问by

I think there must be an attribute to hide a public property from the datagridview. But I can't find it.

我认为必须有一个属性来隐藏 datagridview 的公共属性。但我找不到。

采纳答案by Marc Gravell

If you are adding the columns yourself... don't add the columns you don't want.

如果您自己添加列...不要添加您不想要的列。

If you have AutoCreateColumnsenabled, then:

如果您已AutoCreateColumns启用,则:

  • if it is a class-based model, add [Browsable(false)]to properties you don't want
  • or set the column's .Visibleto false
  • or simply remove the columns you don't want afterwards
  • 如果它是基于类的模型,请添加[Browsable(false)]到您不想要的属性
  • 或将列设置.Visible为 false
  • 或者干脆删除之后不需要的列

回答by Mike J

From your question, I would imagine you don't want to show certain "columns" within the datagridview? If so, use the Columns property to add and remove any automatically created columns that are found on the datasource which you use to attach to the grid.

根据您的问题,我想您不想在 datagridview 中显示某些“列”?如果是这样,请使用 Columns 属性添加和删除在用于附加到网格的数据源上找到的任何自动创建的列。

The DataGridView by default will create columns for all public properties on the underlying data source object. So,

默认情况下,DataGridView 将为基础数据源对象上的所有公共属性创建列。所以,

public class MyClass
{
   private string _name;

   public string Name
   {
      get{ return _name; }
      set { _name = value; }
   }

   public string TestProperty
   {
      { get { return "Sample"; }
   }
}

...
[inside some form that contains your DataGridView class]

MyClass c = new MyClass();

// setting the data source will generate a column for "Name" and "TestProperty"
dataGridView1.DataSource = c;

// to remove specific columns from the DataGridView
// dataGridView1.Columns.Remove("TestProperty")