Groups | Blog | Home
all groups > asp.net webcontrols > december 2007 >

asp.net webcontrols : DataBinding In a Custom Control


thoughtcrimes
12/5/2007 9:38:57 AM
Hello:

I am building a DropDownList-type control. I opted for inheriting just
the WebControl class instead of DropDownList class because the child
controls and the rendered HTML will be quite different.

I have an IEnumerable DataSource and the properties DataValueField and
DataTextField which are just strings of the name of properties in
whatever type of objects are in the DataSource. What I would like to
do is loop through the DataSource and create ListItems by copying over
the DataValueFields and DataTextFields to the ListItems' Value and
Text Fields, but I don't know how to do this.

So if I had a class "Cola" with properties "ColaId" and "ColaName" and
set the DataSource to a List (Of Cola) and the DataValueField to
"ColaId" and the DataTextField to "ColaName", and I ran the following
code:

----------
Dim items As New ArrayList()
Dim data As IEnumerable = GetDataSource()

For Each dataItem As Object In data
Dim listItem As New myListItem
listItem.Value = '' ???
listItem.Text = '' ???
Next

Dim itemsCollection As New myListItemsCollection(items)
----------

I would want to end up with an myListItemsCollection containing
several myListItems that had Values and Text s from the List (Of
Cola).

Any help or links would be very much appreciated.

Thanks,


thoughtcrimes
12/5/2007 10:49:11 AM
[quoted text, click to view]

Aha! The DataBinder seems to work well.

listItem.Value =
Convert.ToString(DataBinder.GetPropertyValue(dataItem,
DataValueField))

I don't know if the exception it throws is all that nice, so might
try, catch and throw my own if the DataValueField doesn't exist in the
dataItem object.

If anyone has any links to good tutorials or references on building
custom WebControls please reply.

Thanks,

AddThis Social Bookmark Button