C# DataGridView没有';t更新BindingList中的枚举

C# DataGridView没有';t更新BindingList中的枚举,c#,winforms,datagridview,enums,.net-4.5,C#,Winforms,Datagridview,Enums,.net 4.5,myDataGridView的数据源是一个包含枚举的BindingList。gridview只包含两列:字符串的常规textbox列和枚举的combobox(下拉)列。如果将combobox列绑定到对象的枚举变量,则会出现错误。以下是我的对象的代码: public class FilterProfile { public FilterProfile() { filters = new BindingList<Filter>(); // the list th

my
DataGridView
的数据源是一个包含枚举的
BindingList
。gridview只包含两列:字符串的常规textbox列和枚举的combobox(下拉)列。如果将combobox列绑定到对象的枚举变量,则会出现错误。以下是我的对象的代码:

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
}
为了使DataGridView中所做的更改反映在
filterProfile.filters
中,我需要将两列的
DataPropertyName
属性设置为各自的变量(关键字
类型
)。这适用于
关键字
字符串,但不适用于
类型
枚举

如果我保留行
colFilterType.DataPropertyName=“type”每当创建新行或将鼠标放在下拉列表上时,我都会收到下面的错误。如果我去掉它,每个新创建的过滤器的
类型
设置为
0
,并且从未更新


我不确定是什么原因导致DataError事件,因此不知道如何处理它或在何处中断。

问题是当您关注新行(准备添加新行)时,基础列表中需要一个新对象,此对象默认为
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 };
  };
}
public FilterProfile()
{
filters=new BindingList();//绑定到gridview的列表
filters.AddingNew+=(s,e)=>{
//FilterType的默认值由您决定。
e、 NewObject=newfilter{type=FilterType.SESSION};
};
}

问题在于,当您关注新行(准备添加新行)时,基础列表中需要一个新对象,该对象默认为
null
,该值绑定到新行,当然
ComboBoxCell
无法接受该null值,从而导致遇到异常。解决方案非常简单,我们只需处理
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 };
  };
}
public FilterProfile()
{
filters=new BindingList();//绑定到gridview的列表
filters.AddingNew+=(s,e)=>{
//FilterType的默认值由您决定。
e、 NewObject=newfilter{type=FilterType.SESSION};
};
}

在c中的datagridview中调用dataerror事件#在c中的datagridview中调用dataerror事件#棒极了!我怎样才能对这个答案投两次赞成票?很好地解释了问题和解决方案。有时C#需要一点魔法代码才能工作。太棒了!我怎样才能对这个答案投两次赞成票?很好地解释了问题和解决方案。有时C#需要一些魔法代码才能工作。