1

I have a dropdownlist which i'm binding to DataTable.

  ddlItems.DataSource = dt;
  ddlItems.DataBind();

in the final html I have :

...
<option value="-1">aaa</option>
<option value="-2">bbb</option>
...

But I want to catch the bind event in the DataBound event and to add an attribute to each listItem , so that the Final Html will be :

 ...
    <option value="-1" MyAttr="lalala1" >aaa</option>
    <option value="-2" MyAttr="lalala2" >bbb</option>
    ...

But the signiture of the databound event is :

  protected void ddlItemsDataBound(object sender, EventArgs e)

and e has only :

enter image description here

How can i catch the specific bounded listItem ?

p.s.

I do NOT want to cancel the databound event , and to use regular loop (adding lisItems in a loop)

Royi Namir
  • 144,742
  • 138
  • 468
  • 792
  • "I do NOT want ... to use regular loop (adding ListItems in a loop)". I'm afraid that you have no choice. But adding (non-existing) attributes to ListItems [is bad practise](http://stackoverflow.com/questions/2744455/is-it-a-bad-practice-to-add-extra-attributes-to-html-elements). There might be better approaches if you would tell us what you are actually trying to achieve. – Tim Schmelter Nov 29 '11 at 13:21
  • what is the sender? can you cast it to ListItem? – MBen Nov 29 '11 at 13:31
  • @MBen no ,,, its DropDownList – Royi Namir Nov 29 '11 at 13:38
  • @RoyiNamir : Then cast it, and get the SelectedIndex – MBen Nov 29 '11 at 13:47
  • @MBen It wont work , It bounds all the 6 list items at once !.... – Royi Namir Nov 29 '11 at 13:50
  • I guess as Rick Schott suggested, you need to do it manually. – MBen Nov 29 '11 at 13:56

2 Answers2

3

DropDownList.DataBound event fires after DropDownList.DataBind() is called for the entire DropDownList.

DropDownList.Items are a ListItemCollection that have no events.

You will have to manually loop through the DropDownList.Items collection again or manually build the ListItemCollection and add it then.

NOTE: An alternative that you probably won't like is to extend DropDownList and ListItemCollection and add the events you want.

rick schott
  • 21,012
  • 5
  • 52
  • 81
1

What you want is something similar to GridView.RowDataBound, which doesn't exist for the DropDownList. What you need to do is a foreach loop in the DataBound event, or you can add this feature by building your own custom DropDownList. The only problem with the latter option is Microsoft doesn't always expose the methods you need to override... so I can't advise how easy or hard it would be to do what you want.

Brian Mains
  • 50,520
  • 35
  • 148
  • 257