隐藏DataGridView中符合特定条件

时间:2017-08-07 12:08:00

标签: c# winforms data-binding datagridview bindingsource

我要求已删除的行不应在DataGridView中显示。我已经能够隐藏已删除的行,但不是理想的方式。我无法正确隐藏新行,同时仍能够更改详细信息组框中包含更多信息的绑定对象。这让我怀疑我完全以错误的方式接近这个问题(另一个迹象是我已经搜索了很多,但却找不到任何特别喜欢我的情况)。

目前的方法

我有DataGridView绑定到BindingSource。此BindingSource的DataSource目前是BindingList<T>(但我已尝试过DataTableDataView等其他人,并使用IBindingListView的自定义实现。此外,一组控件(TextBoxes,ComboBoxes等)绑定到Current BindingSource对象(请参阅代码下面的示例屏幕截图)。绑定数据来自WCF服务,而不是来自数据库。

internal enum PersonState
{
    // New rows that have not been "added" yet. Hide from UI.
    New,

    // New rows that have been "added". These should be saved to the server
    Added,

    // Altered rows. These should be updated on the server
    Edited,

    // Deleted rows. Hide from UI and delete from server when saving.
    Deleted,

    // Do nothing
    Unchanged
}

public class Person : INotifyPropertyChanged
{
    // the following properties have code to raise PropertyChanged
    public string Name { get; set; }
    public DateTime BirthDate { get; set; }
    internal PersonState State { get; set; }
}

public void NewPersonButton_Click()
{
    var person = new Person();
    person.State = PersonState.New;
    personList.Add( person );
}

现在,从示例screenshot;如果用户点击&#34;新&#34;,Person类的新实例会添加到支持BindingList<T>的{​​{1}}。此时,他们希望行隐藏在BindingSource(状态为)中,但用户应该能够使用详细信息组框更改值。一旦用户满意(并且信息通过验证),用户可以点击&#34;添加&#34;。只有在此步骤之后,他们才能看到DataGridView中的行(状态更改为已添加)。

经过测试的方法

  1. 我测试过实现一个自定义IBindingListView,它将过滤底层集合(过滤任何State对象,其状态等于New或Deleted)。但是,这似乎阻止了使用详细信息组框进行修改。我尝试了几种方法,例如https://blogs.msdn.microsoft.com/winformsue/2008/05/19/implementing-multi-column-filtering-on-the-ibindinglistview/

  2. 我已使用DataGridView.Rows [i] .Visible = false测试了隐藏行,并手动跟踪哪些行应隐藏/可见。这与自定义IBindingListView具有相同的结果,因为无法将隐藏行设置为当前行。这样可以防止在详细信息组框中编辑信息。

  3. 我没有看到使用直接绑定实现此目的的任何方法。我想我要问的是;有没有人使用绑定实现这样的事情?有没有人对替代方法有任何建议?

1 个答案:

答案 0 :(得分:0)

您是否尝试使用BindingSource来填充您不想要的行?

BindingSource bs = new BindingSource();

private void SetSource()
{
    bs.DataSource = personList.Where(p=>p.State != PersonState.Deleted && p.State != PersonState.New);
    grid.DataSource = bs;
}

public void NewPersonButton_Click()
{
    var person = new Person();
    person.State = PersonState.New;
    personList.Add( person );
    bs.ResetBindings(false);
}
相关问题