views:

280

answers:

2

I'm trying to write a more generic method that will populate either an ASP.NET dropdownlist OR a telerik RadComboBox with states. I'd like to pass the control in as a parameter to the method. I have a DataTable that holds all the states, which I loop through (see below) - I'd like to make this applicable to a Telerik RadComboBox - so I need to change the first parameter, and also the part where I Insert a new ListItem - for Telerik RadComboBox it is new RadComboBoxItem. How can I do this?

public void PopulateStates(DropDownList ddlStates, string country)
{
    ddlStates.Items.Clear();
    DataLookup dl = new DataLookup();
    DataTable dt = dl.GetStatesByCountry(country);
    if (dt != null)
    {
        if (dt.Rows.Count > 0)
        {
            ddlStates.Items.Insert(0, new ListItem(""));
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                ddlStates.Items.Add(new ListItem(dt.Rows[i]["STCD_Descr"].ToString(),
                    dt.Rows[i]["STCD_State_CD"].ToString()));
            }
        }
    }
}
A: 

I looked up the telerik documentation & there doesn't seem to be common way of doing - what you are trying to do.

If it is possible, try using the databinding (setting the DataSource & calling DataBind).
Note: I haven't tried it. But I think that should be supported by both.

shahkalpesh
A: 

Since ListBox and RadComboBox does not have common classes except for the "Control" class you will need to check the actual type.

How about the following code?

public void PopulateStates(Control ddl, string country)
{
    object listItem = new object();
    switch (ddl.GetType().Name)
    {
        case "RadComboBox":
            listItem = listItem as RadComboBoxItem;
            ddl = ddl as RadComboBox;
            break;
        case "ListBox":
            listItem = listItem as ListItem;
            ddl = ddl as ListBox;
            break;
        default:
            return;
    }

    // proceed with your code
}
Genady Sergeev
This seems like it would work, however, when I try to do something like ddlStates.Items.Clear(); (in the "proceed with your code" area - it doesn't recognize that "Items" is a property since it doesn't know what type of control it is at that point - I get a compile time error.
sorry ddl.Items.Clear();
Sorry, you are completely right! I was sleeping while writing this. It will won't work because the base class they share does not have a property called Items. The easiest solution I can see in the moment is to create 2 predefined methods, the first to accept radCombo and the other dropDown.
Genady Sergeev