Reputation: 899
Is there any way to automatically bind a custom class to a given set of web controls? For instance, supposing I have an instance BindableObject
of the class
public class BindableClass
{
public string FirstString { get; set; }
public string SecondString { get; set; }
public bool BooleanValue { get; set; }
}
I would like to be able to (somehow) do
BindableObject.BindToForm(SomeGroupOfControls);
provided I had previously defined what SomeGroupOfControls
is, instead of having to do
txtSomeTextBox.Text = BindableObject.FirstString;
lblSomeTextBox.Text = BindableObject.SecondString;
chkSomeCheckBox.Checked = BindableObject.BooleanValue;
Is this possible somehow?
Upvotes: 2
Views: 635
Reputation: 7944
This article presents a solution using reflection and some utility methods:
http://msdn.microsoft.com/en-us/library/aa478957.aspx
Upvotes: 0
Reputation: 2767
You can use ObjectDataSource class. There is lot of tutorials and examples on the web about how to use it. It works for sure with DetailsView, GridView and FormView. It's very customizable and flexible control, it's very good at separating your presentation model (aspx) from domain model and allows doing what you want - mapping properties of target class to the corresponding Bind expressions in aspx.
Upvotes: 0
Reputation: 46047
I don't think that's a good approach for something like this. Even if you pass in a group of controls, how are you going to know which field to bind to which control? Sure, with a bunch of logic you can probably get it working most of the time, but I really don't think it's worth the amount of work it would require. I don't really see any tangible benefits to doing it that way either.
I would suggest doing it the old tried-and-true way:
Product prod = GetSomeProduct();
txtProductName.Text = prod.ProductName;
txtProductCode.Text = prod.ProductCode;
If you were looking to bind a collection of objects to a datbound control that would be a different story, but there's really no reason to do all of that in your case.
Here's an example of how you can create a bindable collection of objects:
public class Products : CollectionBase
{
public Products()
{
// default constructor
}
public int Add(Product product)
{
return List.Add(product);
}
public void Remove(Product product)
{
List.Remove(product);
}
public class Product
{
private string productName;
public Product(string Name)
{
productName = Name;
}
public string Name
{
get
{
return productName;
}
set
{
productName = value;
}
}
}
}
Upvotes: 1
Reputation: 24719
You can use reflection on both the usercontrol and the object. You would loop through tht object properties, search for a webcontrol in the usercontrol/panel that uses a naming convension. Detect the type of control to be able to set Checked or Text properties.
Upvotes: 0