简体   繁体   中英

Add Items To Sitecore Combobox

I'm creating a Sitecore Sheer UI wizard which has markup like this

<WizardFormIndent>
   <GridPanel ID="FieldsAction" Columns="2" Width="100%" CellPadding="2">
      <Literal Text="Brand:" GridPanel.NoWrap="true" Width="100%" />
      <Combobox ID="Brand" GridPanel.Width="100%" Width="100%">
         <!-- Leave empty as I want to populate available options in code -->
      </Combobox>
   <!-- Etc. -->
</WizardFormIndent>

But I cannot seem to find a way to add options to the combobox "Brand" in the code beside. Does anyone know how to finish the code below?

[Serializable]
public class MySitecorePage : WizardForm
{
    // Filled in by the sheer UI framework
    protected ComboBox Brands;

    protected override void OnLoad(EventArgs e)
    {
        base.OnLoad(e);
        if (!Context.ClientPage.IsEvent)
        {
             IEnumerable<Brand> brandsInSqlDb = GetBrands();

             // this.Brands doesn't seem to have any methods
             // to add options
        }
    }

}

First off, I'm assuming you're using the Sitecore Combobox from Sitecore.Web.UI.HtmlControls (and not the Telerik control for instance)?

Looking in Reflector, it end up doing something like this:

foreach (Control control in this.Controls)
{
    if (control is ListItem)
    {
        list.Add(control);
    }
}

So I'm expecting you'll need to build a loop through your brandsInSqlDb, instantiate a ListItem and add it to your Brands Combobox.Something like

foreach (var brand in brandsInSqlDb)
{
    var item = new ListItem();
    item.Header = brand.Name; // Set the text
    item.Value = brand.Value; // Set the value

    Brands.Controls.Add(item);
}

It should be lowercase B (Combobox not ComboBox). Full namespace is:

protected Sitecore.Web.UI.HtmlControls.Combobox Brands;

Then you can add options, eg:

ListItem listItem = new ListItem();
this.Brands.Controls.Add((System.Web.UI.Control) listItem);
listItem.ID = Sitecore.Web.UI.HtmlControls.Control.GetUniqueID("ListItem");
listItem.Header = name;
listItem.Value = name;
listItem.Selected = name == selectedName;

The way I do it is to 1st access the Combo box from the page:

ComboBox comboBox = Page.Controls.FindControl("idOfYourComboBox") as ComboBox

Now you got the access to the control you defined in your page. All now you have to do is to assign value to it:

 foreach (var brand in brandsInSqlDb)
{
    comboBox .Header = brand.Name; // Set the text
    comboBox .Value = brand.Value; // Set the value
    Brands.Controls.Add(item);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM