Home / Community & Support / Knowledge Base / RadControls for ASP.NET and ASP.NET AJAX / Grid / "Load on demand" grid with static headers inside RadComboBox

"Load on demand" grid with static headers inside RadComboBox

Article Info

Rating: 5

Article information

Article relates to

RadGrid & RadComboBox "classic"
RadGrid AJAX & RadComboBox AJAX
Telerik.Web.UI 2007.3.1425 

Created by

Stephen, Telerik

Last modified by

Veskoni, Telerik


HOW-TO
Create "Load on demand" grid with static headers inside RadComboBox

DESCRIPTION
This might be is a swift solution when you want to type a string sequence/number in the combobox input and load data (which matches the given pattern) in a table structure inside the combobox dropdown. The integration between RadGrid and RadComboBox in this case extends the built-in multi-column combobox feature by feeding the combo with data loaded on demand. Furthermore, when you scroll to navigate through the loaded records the table headers will remain static at the top for better user experience.

SOLUTION
The key points are depicted below:

  1. Wrap the grid instance in item template of the combobox (do not forget to add one default item with empty text to the combobox - thus the template will be instantiated properly)
  2. Subscribe to the OnClientDropDownOpening event of the combobox in order to populate the grid with the relevant data.
    Note that in this example the AjaxRequest(eventSource, eventTarget) (ajaxRequest(args) for Prometheus) method will be fired only when the user types more than 2 numbers in the combo input. This prevents loading extremely large number of records at once which will cause unpleasant delays. You can modify this logic or remove it if it is not applicable in your case.
  3. Intercept the ajax request in the RaisePostBackEvent (RadAjaxManager1_AjaxRequest for Prometheus) handler of the page (when the source control is the grid control) and filter the data to display order names which match the specified order id. The pattern typed by the user is passed through the second argument (e.Argument for Prometheus) of the RaisePostBackEvent (RadAjaxManager1_AjaxRequest for Prometheus) handler.
  4. Hook the OnRowClick client event of the grid and retrieve the data from the clicked row through the KeyValues (KeyValues Prometheus) collection of the active row. Finally, display the data in the combobox input invoking the SetText(stringValue) (set_text(stringValue) for Prometheus) method of RadComboBox.

Review the code snippets below for further details or download the sample application attached at the bottom of this article:


<script type="text/javascript"
var grid; 
 
function onClientDropDownOpening(sender, eventArgs) 
    var comboText = sender.get_text(); 
                  
     if(comboText.length > 2) 
     { 
         $find("<%= RadAjaxManager1.ClientID %>").ajaxRequest("LoadFilteredData," + comboText); 
     } 
    else 
    { 
        eventArgs.set_cancel(true); 
    } 
 
function gridCreated(sender, eventArgs) 
    grid = sender
 
function rowClicked(sender, args) 
     var cellValues = args.getDataKeyValue("OrderID") + ", " + args.getDataKeyValue("ProductName") + ", $" + args.getDataKeyValue("UnitPrice"); 
     var combo = $find("<%= RadComboBox1.ClientID %>"); 
     setTimeout(function() 
     { 
         combo.set_text(cellValues); 
     }, 50); 
</script>         
<telerik:RadComboBox ID="RadComboBox1"  
MarkFirstMatch="true" 
AllowCustomText="true" 
Width="300px" 
DropDownWidth="500px" 
OnClientDropDownOpening="onClientDropDownOpening" 
runat="server"
    <CollapseAnimation Duration="200" Type="OutQuint" /> 
    <ExpandAnimation Type="OutQuart" /> 
    <ItemTemplate> 
        <telerik:RadGrid ID="RadGrid1"  
        Width="99%"                     
        runat="server" OnNeedDataSource="RadGrid1_NeedDataSource"
            <MasterTableView NoMasterRecordsText=""  
            AutoGenerateColumns="false"  
            ClientDataKeyNames="OrderID,ProductName,UnitPrice" 
            Width="99%"
                <Columns> 
                    <telerik:GridBoundColumn HeaderText="OrderID" DataField="OrderID" UniqueName="OrderID"></telerik:GridBoundColumn>  
                    <telerik:GridBoundColumn HeaderText="ProductName" DataField="ProductName" UniqueName="ProductName" /> 
                    <telerik:GridBoundColumn HeaderText="UnitPrice" DataField="UnitPrice" UniqueName="UnitPrice" 
                        DataFormatString="{0:$###,###.##}" /> 
                </Columns> 
            </MasterTableView> 
            <ClientSettings> 
                <ClientEvents OnRowClick="rowClicked" OnGridCreated="gridCreated" /> 
                <Scrolling AllowScroll="true" UseStaticHeaders="true" ScrollHeight="400px" /> 
            </ClientSettings> 
        </telerik:RadGrid> 
    </ItemTemplate> 
    <Items> 
        <telerik:RadComboBoxItem runat="server" /> 
    </Items> 
</telerik:RadComboBox> 
<telerik:RadAjaxManager ID="RadAjaxManager1"  
runat="server"  
OnAjaxRequest="RadAjaxManager1_AjaxRequest"
</telerik:RadAjaxManager> 


VB:

Public Shared connectionString As String = "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" + System.Web.HttpContext.Current.Server.MapPath("~/App_Data/Nwind.mdb"
 
    Protected Sub Page_Load(ByVal sender As ObjectByVal e As EventArgs) Handles Me.Load 
        Dim grid As RadGrid = TryCast(RadComboBox1.Items(0).FindControl("RadGrid1"), RadGrid) 
        RadAjaxManager1.AjaxSettings.AddAjaxSetting(RadAjaxManager1, grid) 
    End Sub 
 
    Protected Sub RadAjaxManager1_AjaxRequest(ByVal sender As ObjectByVal e As Telerik.Web.UI.AjaxRequestEventArgs) 
        Dim grid As RadGrid = TryCast(RadComboBox1.Items(0).FindControl("RadGrid1"), RadGrid) 
        If e.Argument.IndexOf("LoadFilteredData") <> -1 Then 
            grid.Rebind() 
        End If 
    End Sub 
    Protected Sub RadGrid1_NeedDataSource(ByVal source As ObjectByVal e As GridNeedDataSourceEventArgs) 
        If RadComboBox1.Text <> "" Then 
            CType(source, RadGrid).DataSource = GetDataTable("SELECT [Order Details].OrderID, Products.ProductName, [Order Details].UnitPrice FROM Products, [Order Details] WHERE [Order Details].OrderID LIKE '" + RadComboBox1.Text + "%' AND Products.ProductID=[Order Details].ProductID"
        Else 
            CType(source, RadGrid).DataSource = New Object() {} 
        End If 
    End Sub 
 
    Public Shared Function GetDataTable(ByVal query As StringAs DataTable 
        Dim connection1 As New OleDbConnection(connectionString) 
        Dim adapter1 As New OleDbDataAdapter(query, connection1) 
 
        Dim table1 As New DataTable() 
        connection1.Open() 
        Try 
            adapter1.Fill(table1) 
        Finally 
            connection1.Close() 
        End Try 
        Return table1 
    End Function 

C#

public static string connectionString = "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" + System.Web.HttpContext.Current.Server.MapPath("~/App_Data/Nwind.mdb"); 
     
    protected void Page_Load(object sender, EventArgs e) 
    { 
        RadGrid grid = RadComboBox1.Items[0].FindControl("RadGrid1"as RadGrid; 
        RadAjaxManager1.AjaxSettings.AddAjaxSetting(RadAjaxManager1, grid); 
    } 
    protected void RadAjaxManager1_AjaxRequest(object sender, Telerik.Web.UI.AjaxRequestEventArgs e) 
    { 
        RadGrid grid = RadComboBox1.Items[0].FindControl("RadGrid1"as RadGrid; 
        if (e.Argument.IndexOf("LoadFilteredData") != -1) 
        { 
            grid.Rebind(); 
        } 
    } 
    protected void RadGrid1_NeedDataSource(object source, GridNeedDataSourceEventArgs e) 
    { 
        if (RadComboBox1.Text != ""
        { 
           ((RadGrid)source).DataSource = GetDataTable("SELECT [Order Details].OrderID, Products.ProductName, [Order Details].UnitPrice FROM Products, [Order Details] WHERE [Order Details].OrderID LIKE '" + RadComboBox1.Text + "%' AND Products.ProductID=[Order Details].ProductID"); 
        } 
        else 
        { 
            ((RadGrid)source).DataSource = new object[0] { }; 
        } 
    } 
 
    public static DataTable GetDataTable(string query) 
    { 
        OleDbConnection connection1 = new OleDbConnection(connectionString);         
        OleDbDataAdapter adapter1 = new OleDbDataAdapter(query, connection1); 
         
        DataTable table1 = new DataTable(); 
        connection1.Open(); 
        try 
        { 
            adapter1.Fill(table1); 
        } 
        finally 
        { 
            connection1.Close(); 
        } 
        return table1; 
    } 



<script type="text/javascript"
                var grid; 
                function GridCreated() 
                { 
                    grid = this
                } 
 
                function RowClicked(rowIndex) 
                { 
                  var cellValues = this.Rows[rowIndex].KeyValues["OrderID"]+ ", " + this.Rows[rowIndex].KeyValues["ProductName"] + ", $" + this.Rows[rowIndex].KeyValues["UnitPrice"]; 
                  var combo = <%= RadComboBox1.ClientID %>
                  setTimeout(function()  
                  { 
                    combo.SetText(cellValues); 
                  }, 0); 
                } 
                function HandleOpen(combobox) 
                { 
                  var inputElement = document.getElementById(combobox.InputID); 
                   
                  if(inputElement.value.length > 2) 
                  { 
                    setTimeout(function(){ 
                      grid.AjaxRequest(grid.UniqueID, "LoadFilteredData," + inputElement.value); 
                    }, 0); 
                  } 
                  else 
                  { 
                    return false; 
                  } 
                } 
            </script> 
            <br/> 
            Type at least three digits in the combobox input to search for order (for  
            example 104__): 
            <br/> 
            <br/> 
            <radc:RadComboBox id="RadComboBox1" Width="300px" runat="server" MarkFirstMatch="True" AllowCustomText="True" 
                OnClientDropDownOpening="HandleOpen"
                <ItemTemplate> 
                    <radg:RadGrid id="RadGrid1" Width="295px" runat="server" EnableAJAX="true" EnableAJAXLoadingTemplate="true"
                        <MasterTableView NoMasterRecordsText="" AutoGenerateColumns="False" DataKeyNames="OrderID, ProductName, UnitPrice" 
                            Width="99%"
                            <Columns> 
                                <radg:GridBoundColumn HeaderText="OrderID" DataField="OrderID" UniqueName="OrderID" /> 
                                <radg:GridBoundColumn HeaderText="ProductName" DataField="ProductName" UniqueName="ProductName" /> 
                                <radg:GridBoundColumn HeaderText="UnitPrice" DataField="UnitPrice" UniqueName="UnitPrice" DataFormatString="{0:$###,###.##}" /> 
                            </Columns> 
                        </MasterTableView> 
                        <ClientSettings EnableClientKeyValues="true"
                            <ClientEvents OnRowClick="RowClicked" OnGridCreated="GridCreated"></ClientEvents> 
                            <Scrolling AllowScroll="true" UseStaticHeaders="true" ScrollHeight="400px" /> 
                        </ClientSettings> 
                    </radg:RadGrid> 
                </ItemTemplate> 
                <Items> 
                    <radc:RadComboBoxItem></radc:RadComboBoxItem> 
                </Items> 
            </radc:RadComboBox> 

VB:

        Protected Sub RadGrid1_NeedDataSource(ByVal source As System.ObjectByVal e As Telerik.WebControls.GridNeedDataSourceEventArgs)  
            If RadComboBox1.Text <> "" Then 
                Dim vals As String() = RadComboBox1.Text.Split(",")  
                If (vals.Length > 0) Then 
                    RadComboBox1.Text = vals(0)  
                End If 
                CType([source], RadGrid).DataSource = GetDataTable(("SELECT [Order Details].OrderID, Products.ProductName, [Order Details].UnitPrice FROM Products, [Order Details] WHERE [Order Details].OrderID LIKE '" + RadComboBox1.Text + "%'" + " AND Products.ProductID=[Order Details].ProductID"))  
            Else 
                CType([source], RadGrid).DataSource = New Object(0) {}  
            End If 
        End Sub 
 
        Protected Overrides Sub RaisePostBackEvent(ByVal source As IPostBackEventHandler, ByVal eventArgument As String)  
            MyBase.RaisePostBackEvent([source], eventArgument)  
            If source Is CType(RadComboBox1.Items(0).FindControl("RadGrid1"), RadGrid) And eventArgument.IndexOf("LoadFilteredData") <> -1 Then 
                CType([source], RadGrid).Rebind()  
            End If 
        End Sub 
 
        Public Shared connectionString As String = "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" & System.Web.HttpContext.Current.Server.MapPath("~/Controls/Data/Access/Nwind.mdb")  
 
        Public Shared Function GetDataTable(ByVal query As StringAs DataTable  
            Dim connection1 As New OleDbConnection(connectionString)  
            Dim adapter1 As New OleDbDataAdapter  
            adapter1.SelectCommand = New OleDbCommand(query, connection1)  
            Dim table1 As New DataTable  
            connection1.Open()  
            Try 
                adapter1.Fill(table1)  
            Finally 
                connection1.Close()  
            End Try 
            Return table1  
        End Function 
 
        Private Sub Page_Load(ByVal sender As ObjectByVal e As System.EventArgs) Handles MyBase.Load  
            Dim grid As RadGrid = CType(RadComboBox1.Items(0).FindControl("RadGrid1"), RadGrid)  
            AddHandler grid.NeedDataSource, AddressOf RadGrid1_NeedDataSource  
        End Sub 'Page_Load  


C#:

        protected void RadGrid1_NeedDataSource(object source, Telerik.WebControls.GridNeedDataSourceEventArgs e)  
        {  
            if (RadComboBox1.Text != "")  
            {  
                String [] vals = RadComboBox1.Text.Split(',');  
                if(vals.Length > 0)  
                {  
                    RadComboBox1.Text = vals[0];   
                }  
                ((RadGrid)source).DataSource = GetDataTable("SELECT [Order Details].OrderID, Products.ProductName, [Order Details].UnitPrice FROM Products, [Order Details] WHERE [Order Details].OrderID LIKE '" + RadComboBox1.Text + "%'" + " AND Products.ProductID=[Order Details].ProductID");  
            }  
            else 
            {  
                ((RadGrid)source).DataSource = new object[0];  
            }  
        }  
 
        protected override void RaisePostBackEvent(IPostBackEventHandler source, string eventArgument)  
        {  
            base.RaisePostBackEvent(source, eventArgument);  
            if (source == (RadGrid)RadComboBox1.Items[0].FindControl("RadGrid1") && eventArgument.IndexOf("LoadFilteredData") != -1)  
            {  
                 ((RadGrid)source).Rebind();  
            }  
        }  
        public static string connectionString = "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" + System.Web.HttpContext.Current.Server.MapPath("~/Controls/Data/Access/Nwind.mdb");  
 
        public static DataTable GetDataTable(string query)  
        {  
            OleDbConnection connection1 = new OleDbConnection(connectionString);  
            OleDbDataAdapter adapter1 = new OleDbDataAdapter();  
            adapter1.SelectCommand = new OleDbCommand(query, connection1);  
            DataTable table1 = new DataTable();  
            connection1.Open();  
            try 
            {  
                adapter1.Fill(table1);  
            }  
            finally 
            {  
                connection1.Close();  
            }  
            return table1;  
        }  
 
        protected void Page_Load(object sender, EventArgs e)  
        {  
            RadGrid grid = (RadGrid)RadComboBox1.Items[0].FindControl("RadGrid1");  
            grid.NeedDataSource += new GridNeedDataSourceEventHandler(RadGrid1_NeedDataSource);  
        } 

Comments

If you'd like to comment on this KB article, please, send us a Support Ticket.
Thank you!

Please Sign In to rate this article.