I have problem with databinding in the Win.Forms DataGridView control. Example:
public class A
{
public String Title {get; set; }
public B BField { get; set; }
}
public class B
{
public String Name { get; set; }
}
I want to see in my column value from B. (BField.Name
).
I tried to use the next way for data key, just fill with BField.Name
value, but it doesn't work for me. Else I want to have opportunity for chaning this field value via DataGridView.
Also I tried to create:
class A
{
...
public String BField_Name
{
get{return BField.Name;}
开发者_StackOverflow set{BField.Name = value;}
}
}
But it doesn't work too. Can you help me to fix this problem?
Thanks!
With The Best Regards, Alexander.
To have the "B" class value show correctly in the Grid, override the ToString method to return the Title property.
You can then create a TypeConvertor for the "B" class so the Grid knows how to translate the string cell value into a "B" class type, i.e.
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);
}
}
Then you can apply the converter to the "B" class property of your "A" class, i.e.
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;
}
}
精彩评论