2

我正在使用数据源来用数据填充我的 datagridview。但是,我试图找到一种方法让用户能够隐藏他不想看到的列。

我可以在程序运行之前隐藏和显示列,使用:

[Browsable(false)]
public string URL
{
    get
    {
        return this._URL;
    }
    set
    {
        this._URL = value;
        this.RaisePropertyChnaged("URL");
    }
}

我似乎无法弄清楚如何[Browsable(false)]在运行时更改。

任何想法我怎么能做到这一点?

基本上,我想将“开/关”绑定到菜单。

抱歉,如果我在解释我的问题时没有使用正确的术语,我是自学并在几周前开始的 - 所以还是很新手:)

编辑:

无法隐藏该列,因为当我运行更新功能时,所有列都会再次出现。这是我的更新功能:

    private void UpdateResults()
    {
        Invoke(new MethodInvoker(
                       delegate
                       {
                           this.dgvResults.SuspendLayout();
                           this.dgvResults.DataSource = null;
                           this.dgvResults.DataSource = this._mySource;
                           this.dgvResults.ResumeLayout();
                           this.dgvResults.Refresh();
                       }
                       ));
    }
4

3 回答 3

1

在运行时,您可以将列指定为不可见:

dgv.Columns["ColumnName"].Visible = false;
于 2012-08-15T14:26:47.120 回答
0

确实,正如其他人提到的目的BrowsableAttribute不同,但我了解您想要做什么:

假设我们要创建一个 UserControl,而不是包装 aDataGridView并让用户能够选择要显示的列,从而实现完整的运行时绑定。一个简单的设计是这样的(我正在使用 a ,但如果这是你想要的ToolStrip,你可以随时使用 a ):MenuStrip

在此处输入图像描述

    private void BindingSource_ListChanged(object sender, ListChangedEventArgs e) {
        this.countLabel.Text = string.Format("Count={0}", this.bindingSource.Count);
        this.columnsToolStripButton.DropDownItems.Clear();

        this.columnsToolStripButton.DropDownItems.AddRange(
            (from c in this.dataGrid.Columns.Cast<DataGridViewColumn>()
             select new Func<ToolStripMenuItem, ToolStripMenuItem>(
                 i => {
                     i.CheckedChanged += (o1, e2) => this.dataGrid.Columns[i.Text].Visible = i.Checked;
                     return i;
                 })(
                 new ToolStripMenuItem {
                     Checked = true,
                     CheckOnClick = true,
                     Text = c.HeaderText
                 })).ToArray());
    }

在这种情况下,bindingSource是实例的中介DataSourcedataGrid我正在响应bindingSource.ListChanged.

于 2012-08-15T14:36:55.600 回答
0

在运行时正确执行此操作的方法是在集合上提供自定义 ITypedList 实现,或者为类型提供 TypeDescriptionProvider,或者(对于单对象绑定,而不是列表)来实现 ICustomTypeDescriptor。此外,您需要提供自己的过滤后的 PropertyDescriptor 实现。是不是真的值得吗?在大多数情况下:没有。正确配置网格要容易得多,只需选择要添加的列即可显示(或不显示)适当的列。

于 2012-08-15T14:39:09.780 回答