Programmatically Adding An Item To The DataList

U

Umut K.

Hi all,
I've a DataList control and it's DataBound by a SqlDataReader...
The Reader returns say 3 records and as expected the datalist shows 3 rows.
What i want to do is to add another extra Record (which is not neccesarily a
database record..) but it'll be shown up as an ordinary item in the datalist
rendered as an Item or AlternatingItem ...
Is there a way to do this?

Thanks
 
B

Bench Wang

Try to fill DataList with a loop and then add the extra record.
Or override PreRender event of DataList and add the extra record.
Hope this helps.
 
U

Umut K.

Thank you,
That's what i'm avoiding to do... (but seems like the only way i have .. )
Why isn't it allowed myDataList.Items.Add(new DataListItem()...... ) or
smtg. like this..
??
Any other ideas?
 
J

Jay B. Harlow [MVP - Outlook]

Umut,
For a System.Web.UI.WebControls.DropDownList, I use something similar to:

Dim Data As DataSet
Dim lst As DropDownList
lst.DataMember = "MyMember"
lst.DataTextField = "FieldName"
lst.DataSrouce = Data

DataBind()

lst.Items.Insert(0, New ListItem("<select item>", ""))

I use the above in the Page Load event, which adds the <select item> to the
top of the drop down list. Notice that I call DataBind before I add the
extra item.

I would expect a DataList to work the same way.

Hope this helps
Jay
 
U

Umut K.

Yes, while this works great for the DropDownList,
System.Web.UI.WebControls.DataList doesn't allow sucha method like Insert...
I mean ther's no method like Insert or Add (or am i missing something?)
 
J

Jay B. Harlow [MVP - Outlook]

Umut,
Doh! I don't see an Add or Insert on the DataListItemCollection either.

Curious that they are different, must be some reason. (shrug)

Two options I would consider instead then.

1. Use the SqlDataReader to populate a DataTable, add your row to the
DataTable, then bind to the DataTable.
2. Create a 'Proxy' Data reader that returns the values out of a contained
SqlDataReader, plus the extra row. This class would implement the
IDataReader, IDataRecord, IDisposable, and IEnumerable interfaces.
Delegating most calls to the contained SqlDataReader, however it would
return one or two records first or last... Similar to how the
System.IO.Stream classes work, where you can chain one stream to second
stream chained to a third stream...

I haven't done a lot with DataLists, maybe there is an easier way.

Hope this helps
Jay
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,768
Messages
2,569,574
Members
45,051
Latest member
CarleyMcCr

Latest Threads

Top