New to Telerik UI for ASP.NET AJAXStart a free 30-day trial

Conditional Data Binding based on the selected SearchContext

Environment

ProductTelerik WebForms SearchBox for ASP.NET AJAX

Description

How can I assign a different data source to the Telerik WebForms SearchBox based on the selected SearchContext?

I want the users to be able to select a SearchContext. For instance, they could select between Landlords, Tenants, or Owners and make the SearchBox search from the tables/data sources relative to the selected SearchContext.

Solution

The Telerik WebForms SearchBox implements the ICallbackEventHandler Interface and will make a CallBack sending the ID and Parameters in the Request.Form. For more information on the CallBacks, you can check out the Script Callbacks in ASP.NET article.

The following information is sent with the CallBack:

  • Request.Form["__CALLBACKID"] - contains the ID of the Control that makes the CallBack.
  • Request.Form["__CALLBACKPARAM"] - contains the CallBack parameters.

First, create two Classes that will be used to parse the CallBack parameters.

C#
public class SBCallBackParams
{
    public SBContextItem SelectedContextItem { get; set; }
}

public class SBContextItem
{
    public string Text { get; set; }
    public string Key { get; set; }
}

In the Page's Load event, listen to the CallBack request and serialize the parameters. Once done, you can setup a condition to assign different data sources to the SearchBox based on the selected SearchContext.

C#
protected void Page_Load(object sender, EventArgs e)
{
    if (IsCallback)
    {
        string callBackId = Request.Form["__CALLBACKID"];
        string callBackParams = Request.Form["__CALLBACKPARAM"];

        if (callBackId == RadSearchBox1.ID)
        {
            AdvancedJavaScriptSerializer serializer = new AdvancedJavaScriptSerializer();
            SBCallBackParams sbCallBackParams = serializer.Deserialize<SBCallBackParams>(callBackParams);
            SBContextItem selectedContextItem = sbCallBackParams.SelectedContextItem;

            if (selectedContextItem != null)
            {
                switch (selectedContextItem.Text)
                {
                    case "Landlords":
                        RadSearchBox1.DataSource = GetLandLors();
                        break;

                    case "Tenants":
                        RadSearchBox1.DataSource = GetTenants();
                        break;

                    case "Owners":
                        RadSearchBox1.DataSource = GetOwners();
                        break;
                }
            }
            else
            {
                RadSearchBox1.DataSource = GetAllData();
            }

            RadSearchBox1.DataBind();
        }
    }
}
In this article
EnvironmentDescriptionSolution
Not finding the help you need?
Contact Support