Question

I am using a gridview which is having dropdownlist in edittemplate field. There are 3 list items in dropdown : Red,Amber,Green. Instead of displaying text in listitems, I want to show the colors, for the same I am using dropdownlist's onLoad event, however this event is not able to recognize the dropdownlist. Dropdownlist Designer code :

<asp:TemplateField HeaderText="Color">
<EditItemTemplate> 
  <asp:DropDownList ID="ddlcolor" runat="server" AppendDataBoundItems="true" DataTextField="COLOR" DataValueField ="COLOR" OnLoad="DDLColor_Load">
            <asp:ListItem Value="-1">- Select Color -</asp:ListItem>
            <asp:ListItem Value="0">Amber</asp:ListItem>
            <asp:ListItem Value="1">Green</asp:ListItem>
            <asp:ListItem Value="2">Red</asp:ListItem>                
  </asp:DropDownList></EditItemTemplate></asp:TemplateField>

Dropdownlist onLoad Event in codebehing :

  protected void DDLColor_Load(object sender, EventArgs e)
{

    for (int i = 0; i < ddlcolor.Items.Count; i++)
    {
        ddlcolr.Items[i].Attributes.Add("style", "background-color:" + ddlcolor.Items[i].Text);

    }
} 

However, it shows that the dropdownlist ddlcolor does not exists in current context. Do I need to find this control in gridview ? Please suggest.

Was it helpful?

Solution

You are right. You need to find the control. Using the sender argument will help you locate the drop down without using the find control method

 protected void DDLColor_Load(object sender, EventArgs e)
 {
    DropdownList ddlcolr=(Dropdownlist)sender;
for (int i = 0; i < ddlcolor.Items.Count; i++)
  {
    ddlcolr.Items[i].Attributes.Add("style", "background-color:" + ddlcolor.Items[i].Text);

  }
 } 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top