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)

6
  • "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. There might be better approaches if you would tell us what you are actually trying to achieve. Commented Nov 29, 2011 at 13:21
  • what is the sender? can you cast it to ListItem? Commented Nov 29, 2011 at 13:31
  • @MBen no ,,, its DropDownList Commented Nov 29, 2011 at 13:38
  • @RoyiNamir : Then cast it, and get the SelectedIndex Commented Nov 29, 2011 at 13:47
  • @MBen It wont work , It bounds all the 6 list items at once !.... Commented Nov 29, 2011 at 13:50

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.