views:

871

answers:

6

I would like to use a component that exposes the datasource property, but instead of supplying the datasource with whole list of objects, I would like to use only simple object. Is there any way to do this ?

The mentioned component is DevExpress.XtraDataLayout.DataLayoutControl - this is fairly irrelevant to the question though.

+6  A: 

Databinding expects an IEnumerable object, because it enumorates over it just like a foreach loop does.

So to do this, just wrap your single object in an IEnumerable.

Even this would work:

DataBindObject.DataSource = new List<YourObject>().Add(YourObjectInstance);
FlySwat
+1  A: 

In ASP.NET2.0 you can use the generic collections to make this single object a list of only one object in it that you can databind to any server control using the objectdatasource, e.g.

List<clsScannedDriverLicense> DriverLicenses = new
List<clsScannedDriverLicense>();
//this creates a generic collection for you that you can return from
//your BLL to the ObjectDataSource
DriverLicenses.Add(TheOneObjectThatYouHaveofType_c lsDriverLicense);

Then your ObjectDataSource would look like that:

<asp:ObjectDataSource ID="odsDL" runat="server"
SelectMethod="OrdersByCustomer"
TypeName="YourBLL.UtiltiesClassName"
DataObjectTypeName="clsScannedDriverLicense">
</asp:ObjectDataSource>

Source

Espo
A side note, but people really use ObjectDataSource? I've never seen one use of it outside of MS examples...Its so ugly.
FlySwat
Espo
A: 

Thank you very much. Both of these approaches are workarounds in a way (that is not meant as a criticism BTW). To actually get around this in design time means I will have to create an extra class as a collection for these objects.

Tomas Pajonk
They are not workarounds, because DataSource only takes IENumerable.
FlySwat
Good point. I stand corrected. It is slightly counterintuitive however.
Tomas Pajonk
+1  A: 

I don't think you have much choice other than using an class that implements IEnumerable<T>. Even if the DataSource property was smart enough to take a scalar object, it would probably convert it internally to a vector.

I would however consider using a simple array rather than a List<T> as this will result in fewer memory allocations. If you don't like the array syntax (and also to increase readability) you could use a helper method:

T[] DataSourceHelper::ToVector(T scalar) { return new T[] { scalar }; }

A: 

I'm after the same thing you are. I've posted a new question http://stackoverflow.com/questions/2854234/two-way-databinding-of-a-custom-templated-asp-net-control that has a bit of a lead. See what you can make of it...

uosɐſ
A: 

Using this in my formView:

databoundControl.DataSource = new [] { singleObject };
databoundControl.DataBind();
F.Aquino