在使用数据源时,如何隐藏DataGridView中的C#属性?

31

我认为必须有一种属性可以隐藏 datagridview 中的公共属性,但我找不到它。


1
您可以使用以下链接来满足您的需求:https://dev59.com/jWw05IYBdhLWcg3w4125 - user1547592
3个回答

84

如果您正在自行添加列...请不要添加您不需要的列。

如果启用了AutoCreateColumns,则:

  • 如果它是基于类的模型,请将 [Browsable(false)] 添加到您不需要的属性上
  • 或将列的.Visible设置为false
  • 或者在之后简单地删除您不需要的列

另一种选择是在AutoGeneratingColumn处理程序中将DataGridAutoGeneratingColumnEventArgs.Cancel设置为true。 - Aelian
3
是的,BrowsableAttribute!这就是我整天在找的东西。谢谢。 - Szybki
1
@Szybki 如果我没记错的话,我发现它查找的东西是通过查看反射器...从网格到PropertyDescriptor,再到PropertyInfo。这并不明显;p - Marc Gravell
1
我在哪里可以找到AutoCreateColumns - Daniel Möller
@Daniel 你可能在使用Web控件吗?在撰写本文时,我认为这个问题是关于WinForms的,它具有此属性。 - Marc Gravell
是的,我找到了。该属性被隐藏了(仅通过代码可见,而非设计师)。它被称为“AutoGenerateColumns”。也许将这个答案补充完整会更有趣? - Daniel Möller


0
从你的问题来看,我猜想你不想在数据网格中显示某些“列”?如果是这样,可以使用Columns属性来添加和删除在数据源中自动创建的列,然后将其附加到网格上。
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")

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接