Monday, October 20, 2008

Small Thing Learned Today

So I needed to show a type name in the textbox today. Like 'DateTime', or 'Integer' etc. I decided to create a binding source and bind to System.Type.Name like this:

this.propertyTypeBindingSource.DataSource = typeof(System.Type);
/* snip */
this.nameTextBox.DataBindings.Add(new System.Windows.Forms.Binding
("Text", this.propertyTypeBindingSource, "Name", true));
/* snip */
Type PropertyType = typeof(DateTime);
this.propertyTypeBindingSource.DataSource = PropertyType;

However, when I try to run the application, I get an exception

"Cannot bind to the property or column Name on the DataSource. Parameter name: dataMember"

So, looks like I'm not allowed to bind directly to System.Type. Maybe I have to do some simple trick ... I create a class

public class StubPropertyType
{
public StubPropertyType(Type type)
{
this.StubPropertyTypeName = type.Name;
}
private string _stubPropertyTypeName = string.Empty;
public string StubPropertyTypeName
{
get { return _stubPropertyTypeName; }
set { _stubPropertyTypeName = value; }
}
}

and my binding now looks along these lines:

this.propertyStubBindingSource.DataSource = typeof(StubPropertyType);
/* snip */
this.nameTextBox.DataBindings.Add(new System.Windows.Forms.Binding
("Text", this.propertyStubBindingSource, "StubPropertyTypeName", true));
/* snip */
Type PropertyType = typeof(DateTime);
StubPropertyType stub = new StubPropertyType(PropertyType);
this.propertyStubBindingSource.DataSource = stub;

And it works like a charm!

by . Also posted on my website

No comments: