【问题标题】:DataGridView doesn't update Enum in BindingListDataGridView 不更新 BindingList 中的枚举
【发布时间】:2013-12-03 22:39:46
【问题描述】:

我的DataGridView 的数据源是一个BindingList<Filter>,其中包含一个枚举。 gridview 仅包含两列:字符串的常规文本框列和枚举的组合框(下拉)列。如果我将组合框列绑定到对象的枚举变量,则会出现错误。这是我的对象的代码:

public class FilterProfile
{
   public FilterProfile()
   {
      filters = new BindingList<Filter>();  // the list that gets bound to gridview
   }
   public string name { get; set; }
   public BindingList<Filter> filters { get; set; }
}

public class Filter
{
  public string keyword { get; set; }
  public FilterType type { get; set; }  // the enum in question
}

public enum FilterType : int
{
  SESSION = 1,
  ORDER = 2,
  SHIPMENT = 3
}

我有一个表单,用户从下拉菜单中选择 FilterProfile,然后我从全局列表中找到合适的 FilterProfile 并绑定它:

foreach (PlvFilterProfile filterProfile in _filterProfiles)
     {  
        // find the correct filter profile
        if (filterProfile.name.Equals(lstFilterProfiles.Text))
        {
           // bind it
           grdFilters.DataSource = filterProfile.filters;
           break;
        }
     }

为了使 DataGridView 中所做的更改反映在 filterProfile.filters 中,我需要将两列的 DataPropertyName 属性设置为它们各自的变量(keyword 或 type)。这适用于keyword 字符串,但不适用于type 枚举。

如果我保留colFilterType.DataPropertyName = "type"; 行,每当创建新行或将鼠标放在下拉列表上时,都会出现以下错误。如果我去掉它,每个新创建的过滤器的type 都设置为0 并且永远不会更新。

我不确定导致 DataError 事件的原因,所以不知道如何处理它或在哪里设置断点。

【问题讨论】:

  • 在c#的datagridview中调用dataerror事件

标签: c# winforms datagridview enums .net-4.5


【解决方案1】:

问题是当您关注新行时(准备添加新行),底层列表中需要一个新对象,该对象由null默认,该值绑定到新行并且当然 ComboBoxCell 不能接受该空值,导致您遇到异常。解决方案确实很简单,我们只需要处理BindingList的事件AddingNew,将其中的默认新对象设置为有效值,然后就可以正常工作了:

public FilterProfile()
{
  filters = new BindingList<Filter>();  // the list that gets bound to gridview
  filters.AddingNew += (s,e) => {
    //the default value of FilterType is up to you.
    e.NewObject = new Filter {type = FilterType.SESSION };
  };
}

【讨论】:

  • 太棒了!我怎样才能两次赞成这个答案?很好地解释了问题和解决方案。有时 C# 需要一些神奇的代码才能工作。
猜你喜欢
  • 2013-06-10
  • 2011-03-21
  • 1970-01-01
  • 2021-09-15
  • 1970-01-01
  • 2018-10-27
  • 1970-01-01
  • 2012-12-06
  • 1970-01-01
相关资源
最近更新 更多