Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
291 views
in Technique[技术] by (71.8m points)

c# - How to format individual DropDownlist Items (color, etc.) during onDataBinding event

I have a basic DropDownList bound to a ObjectDataSource:

<asp:DropDownList ID="DropDownList1" runat="server" 
AutoPostBack="True" DataSourceID="objDataSource1" 
DataTextField="FieldName" DataValueField="FieldID" />

The DataTable from which it receives the DataTextField and DataValueField values also returns some other interesting information about the records. Say Active = Y/N for simplicity's sake.

What I'd like to do is to set the background-color property of the DropDownList Item based on that Active field in the DataSource results. Further, I'd like to do this "in the same pass" as when the DropDownList is bound to the data. So my guess is that it has to happen during OnDataBound.

Things I already know/tried:

  1. I could go back and loop through the DropDownList items later. But it would involve embedding loops and re-visiting the DataTable rows and it just seems inefficient

     int row;
     for (row = 0; row < DropDownList1.Items.Count - 1; row++)
     {
        [[if this row = that data row]]
         DropDownList1.Items[row].[[DoStuffHere, etc.]]
     }
    
  2. We already do stuff like this with the GridView OnRowDataBound event, by accessing the GridViewRowEventArgs e. What I seem to be missing is an OnDropDownListItemBound event, so to speak.

Hope I've been clear and concise. Seems as though it should be easy...

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can't do it during OnDataBinding because the data has not actually been bound yet. Your best shot is (1), that is, use OnDataBound and loop through the items.

protected void DropDownList1_DataBound(object sender, EventArgs e)
{
    foreach(ListItem myItem in DropDownList1.Items)
    {
         //Do some things to determine the color of the item
         //Set the item background-color like so:
         myItem.Attributes.Add("style","background-color:#111111");
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...