Populate DropDownList in Column within grid's ItemDataBound event without accessing the database each time

570 views Asked by At

I have a grid in ASP.NET with a column that has DropDownLists in it.

Here is an example of what the grid looks like:
ItemCol | DropDownCol
Item1 | DropDownList
Item2 | DropDownList
Item3 | DropdownList

The only way I know of to populate each DropDownList with its values is in the grid's ItemDataBound event like so:

if (e.Item is GridDataItem)
{
    GridDataItem item = (GridDataItem)e.Item;
    IEnumerable<ProductCategory> productCategoryList = ProductService.GetProductCategories();

    RadComboBox cbProductCategory = item.FindControl("cbProductCategory") as RadComboBox;
    cbProductCategory.DataValueField = "Id";
    cbProductCategory.DataTextField = "CategoryName";
    cbProductCategory.DataSource = productCategoryList;
    cbProductCategory.DataBind();
}

Since we are in the ItemDataBound event I am making a call to the database every time the GetProductCategories function is called.

What is the best way to get my list of Product Categories, store it somewhere, then use the stored version to bind each DropDownList instead?

1

There are 1 answers

0
AzNjoE On BEST ANSWER

You can create a field in your code-behind file and in Page_Load you populate the productCategoryList with the information. That way you only access the database on page_load.

private IEnumerable<ProductCategory> productCategoryList;

protected void Page_Load(object sender, EventArgs e)
{
    if (!Page.IsPostBack)
    {
         productCategoryList = ProductService.GetProductCategories();
    }
}

Then just do your databinding like you have it.