Sunday, December 12, 2010

Remove duplicate Items RadComboBox - Telerik

I had a puzzle recently with a RadComboBox...
I have a sql query that took a long time to run... sometimes 30 seconds, due to the huge database size and the complex query...

To populate a RadGrid - I bound it to a SqlDataSource. But I also needed dropdowns to filter this grid - and this needed to be bound to unique items in a column of that grid... I didnt want to do another db query to get a filtered version of the same info - so I bound it to the SAME SqlDataSource - and cached the datasource to minimize calls.

[asp:SqlDataSource ID="MySqlDataSource" EnableCaching="true" CacheDuration="180"
runat="server" OnSelecting="MySqlDataSource_Selecting"
ConnectionString="[%$ ConnectionStrings:mySqlConnectionString %]"
SelectCommand="SELECT * FROM vwBundlesForSale "]
[/asp:SqlDataSource]

However, this made there to be duplicate items in my dropdown... and the data was not sorted.

If you want to Sort and Filter for unique items in a Telerik RadComboBox, use something like this:

IN ASPX PAGE:

[telerik:RadComboBox ID="CoatComboBox"
runat="server" DataSourceID="MySqlDataSource" DataTextField="CoatName" DataValueField="CoatName" AllowCustomText="false" EnableItemCaching="true" Width="165px" DropDownWidth="260px" OnDataBound="SortAndNoDups_OnDataBound" AppendDataBoundItems="true" ......


IN CS CODE-BEHIND

protected void SortAndNoDups_OnDataBound(object sender, EventArgs e)
{
RadComboBox fixComboBox = (RadComboBox)sender;
string selectedText = string.Empty;
if (fixComboBox.SelectedIndex >= 0)
{
selectedText = fixComboBox.SelectedValue;
}
fixComboBox.SelectedIndex = -1;
fixComboBox.Filter = RadComboBoxFilter.Contains;
fixComboBox.Sort = RadComboBoxSort.Ascending;
fixComboBox.SortItems();
string priorItem = "";
for (int i = 0; i < fixComboBox.Items.Count; i++)
{
try
{
RadComboBoxItem itm = fixComboBox.Items[i];
if (itm.Text == priorItem)
{
fixComboBox.Items.Remove(itm);
i--;
}
else
{
priorItem = itm.Text;
}
}
catch
{
break;
}
}

if (selectedText != string.Empty)
{
try
{
fixComboBox.SelectedValue = selectedText;

}
catch { }
}

}
protected void MySqlDataSource_Selecting(object sender, SqlDataSourceSelectingEventArgs e)
{
e.Command.CommandTimeout = 0; //prevents SqlDataSource timeout after 30 seconds

}