I’m using ASP.NET Webforms. I’m creating functionality to filter products based on their attributes.
The way I’m doing it now is taking too long. I need a better, quicker way.
My current method is the following. I have a GridView, which displays Attribute Names. A CheckBoxList is nested in the ItemTemplate which contains the Attribute Values. The CheckBoxList has autopostback=”true”. On each selectedindexchanged event, I loop through the checkboxes and filter based on the checked state. I then compare the filtered results and the checkbox values and disable the checkboxes which aren’t in the filtered results.
Here’s the code which does that:
protected void cblAttr_SelectedIndexChanged(object sender, EventArgs e)
{
var filteredResults = ProductAttribute.Get(Convert.ToInt32(Request.QueryString["idsite"]));
var selectedAttributes = filteredResults;
foreach (GridViewRow row in gridAttrSet.Rows)
{
foreach (ListItem item in ((CheckBoxList)row.FindControl("cblAttr")).Items)
{
if (item.Selected == true)
{
// filter
selectedAttributes = selectedAttributes.Where(a => a.idAttr == Convert.ToInt32(item.Value)).ToList();
}
}
}
// this will now contain
filteredResults = (from c in filteredResults
join o in selectedAttributes
on c.idProduct equals o.idProduct
select new ProductAttribute
{
idProduct = c.idProduct,
idAttrSet = c.idAttrSet,
idAttr = c.idAttr,
}).ToList();
foreach (GridViewRow row in gridAttrSet.Rows)
{
if (row.RowIndex > ((GridViewRow)((CheckBoxList)sender).NamingContainer).RowIndex)
{
foreach (ListItem item in ((CheckBoxList)row.FindControl("cblAttr")).Items)
{
// disable if filtered out
item.Enabled = !(filteredResults.Where(a => a.idAttr == Convert.ToInt32(item.Value)).ToList().Count == 0);
}
}
}
}
As you can see, there’s alot of looping going on, and there can thousands of records.
What would be a faster way to do this? Any ideas would be appreciated.
Thank you!
The part that was taking time here was the call to the database.