2010-08-10 71 views
0

我在Win.Forms DataGridView控件中存在数据绑定问题。 例子:将复杂属性绑定到DataGridView Win.Forms

public class A 
{ 
     public String Title {get; set; } 
     public B BField { get; set; } 
} 

public class B 
{ 
     public String Name { get; set; } 
} 

我想从B.(BField.Name)我的列值看。 我试图用数据键的下一个方法,只需填写BField.Name值,但它不适用于我。否则,我想通过DataGridView有机会通过此字段值进行链接。

而且我试图创建:

class A 
{ 
... 

     public String BField_Name 
     { 
      get{return BField.Name;} 
      set{BField.Name = value;} 
     } 
} 

但它不工作过。 你能帮我解决这个问题吗?

谢谢!

随着最好的问候, 亚历山大。

+0

您能否为第二个示例定义“它不工作”?我希望它能起作用。 – 2010-08-10 14:54:21

+0

谢谢大家。我在我的代码中发现了问题。对于修复问题,我决定使用例如“public String BField_Name ...”这一行。但转换器也是非常好的主意。 – oivoodoo 2010-08-19 11:08:37

回答

1

要使网格中的“B”类值正确显示,请覆盖返回Title属性的方法ToString

然后,您可以为“B”类中创建一个TypeConvertor所以网格知道如何串单元格的值转换为“B”类的类型,即

public class BStringConvertor : TypeConverter 
    { 
     public BStringConvertor() 
     : base() 
     { 
     } 

     public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) 
     { 
     // Allow conversion from a String type 
     if (sourceType == typeof(string)) 
      return true; 

     return base.CanConvertFrom(context, sourceType); 
     } 

     public override object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value) 
     { 
     // If the source value is a String, convert it to the "B" class type 
     if (value is string) 
     { 
      B item = new B(); 
      item.Title = value.ToString(); 
      return item; 
     } 
     return base.ConvertFrom(context, culture, value); 
     } 

     public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType) 
     { 
     // If the destination type is a String, convert the "B" class to a string 
     if (destinationType == typeof(string)) 
      return value.ToString(); 

     return base.ConvertTo(context, culture, value, destinationType); 
     } 
    } 

然后你可以转换申请您的“A”类的“B”级属性,即

public class A 
    { 
     public string Title { get; set; } 

     [TypeConverter(typeof(BStringConvertor))] 
     public B BField { get; set; } 
    } 

    public class B 
    { 
     public string Title { get; set; } 

     public override string ToString() 
     { 
     return this.Title; 
     } 
    }