开发者

Binding a data source but displaying something else

I have quite a few places where I need to bind form controls directly to a backing database. I'm using LINQ to DataSet to do this.

For example, I have a ComboBox with entries filled in by a database query. The problem is of course that all of my data uses numerical IDs and I need to do a table query to translate this into user-readable options.

Normally I would just join the second table and use the combobox DisplayMember to point at the user-readable string column. This doesn't work because after using join or any projections on the query you're开发者_JS百科 (understandably) unable to convert that query into a DataView.

It's hard to believe that this problem isn't run into by everyone who uses DataView. Is there any way to override my form controls' behavior to make them display a function of their value? Like if their Value is v, then they display SomeMethod(v)?


I don't believe what you are trying to accomplish is possible by means of DisplayMember. Its a property, that's how it was designed. However, there are a few other means to accomplish what you want.

1) You could wireup to the ComboBox's Format event. This is the ideal place to change your databound items into human-readable items for display, and really is exactly what you want.

2) You could use LINQ to SQL classes instead, and override the .ToString() portions in the partial classes to display the data how you want. When you databind to a LINQ to SQL object the ComboBox will display the string value of that object.

Since you are already using LINQ to DataSet, I would just wireup to the Format event, though.


I have a pretty simple approach to these things - if it doesn't play nicely, just invent a view-model, i.e. an object layout designed to make mapping between your domain model and the UI plain sailing. This can also encourage you to populate your data in the correct shape for the view-model, rather than for the domain-model; and this often has decent savings in terms of reducing the number of columns (and sometimes rows) fetched, and (perhaps more importantly) avoiding multiple trips to the DB (by fetching exactly the right data, in one hit, in the right shape).

From a view-model, you can then use simple data-binding techniques, as the data you want is now directly available as first-level values on the view-model.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜