Click here to Skip to main content
15,897,094 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
In my project I generate a list box during runtime. I give a title 'SELECT BLOCK' to that list box at zero index. Can I give a diff color to that title. My code:
C#
DataSet ds1 = new DataSet("block");
             da1.Fill(ds1, "block");
             for (int i = 0; i < ds1.Tables[0].Rows.Count; i++)
             {
                 adds1.Add(ds1.Tables[0].Rows[i].ItemArray[0].ToString());
                 string name1 = ds1.Tables[0].Rows[i]["block_name"].ToString();
             }
             adds1.Sort((x, y) => string.Compare(x, y));
             adds1.Insert(0, "SELECT BLOCK");
             ListBox1.DataSource = adds1;
             ListBox1.DataBind();
             ListBox1.Visible = true;

Can anyone advice?
Regards.
Posted
Updated 16-Jan-13 3:12am
v2

Add this line after you bind your ListBox:
C#
ListBox1.DataBind();
ListBox1.Visible = true;
if(ListBox1.Items.Count>0)
ListBox1.Items[0].Attributes.Add("style", "background-color:Red;");
or
C#
ListBox1.DataBind();
ListBox1.Visible = true;
if(ListBox1.Items.Count>0)
ListBox1.Items[0].Attributes.Add("style", "color:Red;");
 
Share this answer
 
v3
Comments
S.Rajendran from Coimbatore 16-Jan-13 10:20am    
I did as you said like follows:

adds1.Sort((x, y) => string.Compare(x, y));
adds1.Insert(0, "SELECT BLOCK");
ListBox1.DataSource = adds1;
ListBox1.Items[0].BackColor.Attributes.Add("style", "background-color:Red;");
ListBox1.DataBind();

but get error like:
'System.Web.UI.WebControls.ListItem' does not contain a definition for 'BackColor' and no extension method 'BackColor' accepting a first argument of type 'System.Web.UI.WebControls.ListItem' could be found (are you missing a using directive or an assembly reference?)

regards
Zafar Sultan 16-Jan-13 10:48am    
Add that code after databinding. Check my updated reply.
Espen Harlinn 17-Jan-13 16:57pm    
5'ed!
Zafar Sultan 18-Jan-13 2:30am    
Thanks.
I would use a ListView[^] instead of the ListBox.
The ListView provides column titles and allows to change their attributes.
 
Share this answer
 
Comments
Espen Harlinn 17-Jan-13 16:57pm    
Yes! :-D

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900