Add Load on Demand radcombobox within a radgrid

2 Answers 109 Views
ComboBox Grid
cest
Top achievements
Rank 1
Iron
cest asked on 08 Jul 2024, 06:17 PM

I was curious if there was a way to add a radcombobox with load on demand abilities within an exisiting radgrid. I really just need to have it that when you start typing it will then populate any items that start with the letter/numbers you are typing dynamically. For example, if I typed Batt it would autofill Battery or if I had done Serial Number it would populate all that apply. I have seen it outside of a grid but not within. In the picture below would like to have the asset_type autofill options from database that are in the asset_type column.  Any examples would be great.


Imports System.Data
Imports System.Data.SqlClient
Imports System.Drawing
Imports System.Web.UI
Imports System.Configuration
Imports System.Web.UI.WebControls
Imports Telerik.Web.UI

Partial Class RadGridEditCustomValidatorVB
    Inherits Page

    ' Page Load event
    Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
        If Not IsPostBack Then
            RadGrid.Rebind()
        End If
    End Sub

    ' Bind the grid to the data source
    Protected Sub RadGrid_NeedDataSource(sender As Object, e As GridNeedDataSourceEventArgs)
        RadGrid.DataSource = GetGridSource()
    End Sub

    ' Get data from the database
    Private Function GetGridSource() As DataTable
        Dim dataTable As New DataTable()

        ' Get the connection string from the web.config file
        Dim connectionString As String = ConfigurationManager.ConnectionStrings("Data_WarehouseConnectionString_PRODUCTION").ConnectionString
        Using connection As New SqlConnection(connectionString)
            Dim query As String = "SELECT [ID], [Asset_type], [PortalID], [asset_SN], [asset_model], [Maint_Date], [Fill_qty], [asset_location], [Active_indicator], [Asset_Notes] FROM [data_warehouse].[dbo].[ATracker]"
            Using command As New SqlCommand(query, connection)
                Using adapter As New SqlDataAdapter(command)
                    adapter.Fill(dataTable)
                End Using
            End Using
        End Using

        Return dataTable
    End Function

    Protected Sub RadGrid_ItemCreated(sender As Object, e As GridItemEventArgs)
        If e.Item.IsInEditMode Then
            Dim item As GridEditableItem = TryCast(e.Item, GridEditableItem)

            ' Add validator for Asset_type (Non-nullable)
            Dim assetTypeEditor As GridTextBoxColumnEditor = CType(item.EditManager.GetColumnEditor("Asset_type"), GridTextBoxColumnEditor)
            AddRequiredFieldValidator(assetTypeEditor.TextBoxControl, "Asset Type")

            ' Add validator for PortalID (Non-nullable)
            Dim portalIDEditor As GridTextBoxColumnEditor = CType(item.EditManager.GetColumnEditor("PortalID"), GridTextBoxColumnEditor)
            AddRequiredFieldValidator(portalIDEditor.TextBoxControl, "PortalID")

            ' Add validator for asset_sn (Non-nullable)
            Dim assetSNEditor As GridTextBoxColumnEditor = CType(item.EditManager.GetColumnEditor("asset_SN"), GridTextBoxColumnEditor)
            AddRequiredFieldValidator(assetSNEditor.TextBoxControl, "Asset Serial Number")

            ' Add validator for asset_model (Non-Nullable)
            Dim assetModelEditor As GridTextBoxColumnEditor = CType(item.EditManager.GetColumnEditor("asset_model"), GridTextBoxColumnEditor)
            AddRequiredFieldValidator(assetModelEditor.TextBoxControl, "Asset Model")

            ' Add validator for asset_location (Nullable)
            Dim assetLocEditor As GridTextBoxColumnEditor = CType(item.EditManager.GetColumnEditor("asset_location"), GridTextBoxColumnEditor)
            AddRequiredFieldValidator(assetLocEditor.TextBoxControl, "Location")

            ' Add validator for Fill_qty (Nullable but must be numeric if provided)
            Dim fillQtyEditor As GridTextBoxColumnEditor = CType(item.EditManager.GetColumnEditor("Fill_qty"), GridTextBoxColumnEditor)
            AddNumericValidator(fillQtyEditor.TextBoxControl, "Fill Quantity")

            Dim buttonName As String = If(TypeOf item Is IGridInsertItem, "PerformInsertButton", "UpdateButton")
            TryCast(item.FindControl(buttonName), Button).ValidationGroup = "gridFormValidation"
        End If
    End Sub

    Private Sub AddRequiredFieldValidator(textBox As TextBox, fieldName As String)
        Dim validator As New CustomValidator()
        validator.ID = "CustomValidator_" & fieldName.Replace(" ", "_")
        validator.ControlToValidate = textBox.ID
        validator.ValidateEmptyText = True
        validator.ErrorMessage = String.Format("* {0} is required", fieldName)
        validator.ForeColor = Color.OrangeRed
        validator.ClientValidationFunction = "requiredFieldValidation"
        validator.ValidationGroup = "gridFormValidation"
        AddHandler validator.ServerValidate, AddressOf RequiredField_ServerValidate
        textBox.Parent.Controls.Add(validator)
    End Sub

    Private Sub AddNumericValidator(textBox As TextBox, fieldName As String)
        Dim validator As New CustomValidator()
        validator.ID = "CustomValidator_" & fieldName.Replace(" ", "_")
        validator.ControlToValidate = textBox.ID
        validator.ValidateEmptyText = False
        validator.ErrorMessage = String.Format("* {0} must be numeric", fieldName)
        validator.ForeColor = Color.OrangeRed
        validator.ClientValidationFunction = "numericFieldValidation"
        validator.ValidationGroup = "gridFormValidation"
        AddHandler validator.ServerValidate, AddressOf NumericField_ServerValidate
        textBox.Parent.Controls.Add(validator)
    End Sub

    Protected Sub RequiredField_ServerValidate(source As Object, args As ServerValidateEventArgs)
        args.IsValid = Not String.IsNullOrWhiteSpace(args.Value)
    End Sub

    Protected Sub NumericField_ServerValidate(source As Object, args As ServerValidateEventArgs)
        Dim result As Decimal
        args.IsValid = Decimal.TryParse(args.Value.Trim(), result)
    End Sub

    Protected Sub RadGrid_ItemCommand(sender As Object, e As GridCommandEventArgs)
        If e.CommandName = RadGrid.UpdateCommandName Or e.CommandName = RadGrid.PerformInsertCommandName Then
            If Page.IsValid Then
                Dim editableItem As GridEditableItem = TryCast(e.Item, GridEditableItem)

                'Runs Validation Code from RequiredField_ServerValidate and NumericField_ServerValidate
                Dim txtAssetType As TextBox = CType(editableItem("Asset_type").Controls(0), TextBox)
                Dim txtPortalID As TextBox = CType(editableItem("PortalID").Controls(0), TextBox)
                Dim txtSerialNum As TextBox = CType(editableItem("asset_SN").Controls(0), TextBox)
                Dim txtFillQty As TextBox = CType(editableItem("Fill_qty").Controls(0), TextBox)
                Dim rdpMaintDate As RadDatePicker = CType(editableItem("Maint_Date").Controls(0), RadDatePicker)
                Dim txtLocation As TextBox = CType(editableItem("asset_location").Controls(0), TextBox)
                Dim txtModel As TextBox = CType(editableItem("asset_model").Controls(0), TextBox)
                Dim chkActive As CheckBox = CType(editableItem("Active_indicator").Controls(0), CheckBox)
                Dim txtNotes As TextBox = CType(editableItem("Asset_Notes").Controls(0), TextBox)

                Dim objConnection As SqlConnection
                Dim strSQL As String


                objConnection = New SqlConnection(ConfigurationManager.ConnectionStrings("Data_WarehouseConnectionString_PRODUCTION").ConnectionString)

                'Testing DB connection
                'objConnection = New SqlConnection(ConfigurationManager.ConnectionStrings("masterConnectionString").ConnectionString)

                'Determine if we are updating or inserting
                If e.CommandName = RadGrid.UpdateCommandName Then
                    strSQL = "UPDATE [data_warehouse].[dbo].[ATracker] SET [Asset_type] = @asset_type, [PortalID] = @PortalID, [asset_SN] = @AssetSN, [Fill_qty] = @FillQty, [Maint_Date] = @MaintDate, [asset_location] = @Location, [asset_model] = @Model, [Active_indicator] = @Active, [Asset_Notes] = @Notes WHERE [ID] = @ID"
                Else
                    strSQL = "INSERT INTO [data_warehouse].[dbo].[ATracker] ([Asset_type], [PortalID], [asset_SN], [Fill_qty], [Maint_Date], [asset_location], [asset_model], [Active_indicator], [Asset_Notes]) VALUES (@asset_type, @PortalID, @AssetSN, @FillQty, @MaintDate, @Location, @Model, @Active, @Notes)"
                End If

                'Add parameters to the SQL command
                Dim cmd As New SqlCommand(strSQL, objConnection)
                cmd.Parameters.Add("@asset_type", SqlDbType.VarChar, 20).Value = txtAssetType.Text
                cmd.Parameters.Add("@ID", SqlDbType.Int).Value = If(e.CommandName = RadGrid.UpdateCommandName, editableItem.GetDataKeyValue("ID"), DBNull.Value)
                cmd.Parameters.Add("@PortalID", SqlDbType.VarChar, 10).Value = txtPortalID.Text
                cmd.Parameters.Add("@AssetSN", SqlDbType.VarChar, 20).Value = txtSerialNum.Text
                cmd.Parameters.Add("@FillQty", SqlDbType.Int).Value = If(String.IsNullOrEmpty(txtFillQty.Text), DBNull.Value, Convert.ToInt32(txtFillQty.Text))
                cmd.Parameters.Add("@MaintDate", SqlDbType.Date).Value = If(rdpMaintDate.SelectedDate Is Nothing, DBNull.Value, rdpMaintDate.SelectedDate)
                cmd.Parameters.Add("@Location", SqlDbType.VarChar, 20).Value = txtLocation.Text
                cmd.Parameters.Add("@Model", SqlDbType.VarChar, 20).Value = txtModel.Text
                cmd.Parameters.Add("@Active", SqlDbType.Bit).Value = chkActive.Checked
                cmd.Parameters.Add("@Notes", SqlDbType.VarChar, -1).Value = txtNotes.Text

                Try
                    objConnection.Open()
                    cmd.ExecuteNonQuery()
                Catch ex As Exception
                    System.Console.WriteLine(ex.ToString())
                Finally
                    objConnection.Close()
                End Try

                RadGrid.Rebind()
            Else
                e.Canceled = True
            End If
        End If
    End Sub


    'CANT GET THIS TO TRIGGER
    Protected Sub RadGrid_ItemDeleted(sender As Object, e As GridCommandEventArgs)
        If e.CommandName = RadGrid.DeleteCommandName Then
            Dim item As GridDataItem = TryCast(e.Item, GridDataItem)

            If item IsNot Nothing Then
                ' Find the hidden field in the grid data item where ID is bound
                Dim atID As Integer = Convert.ToInt32(item.OwnerTableView.DataKeyValues(item.ItemIndex)("ID"))

                Dim objConnection As SqlConnection
                Dim strSQL As String

                objConnection = New SqlConnection(ConfigurationManager.ConnectionStrings("Data_WarehouseConnectionString_PRODUCTION").ConnectionString)

                ' SQL command to delete the record where ID matches
                strSQL = "DELETE FROM [data_warehouse].[dbo].[ATracker] WHERE [ID] = @ID"

                Dim cmd As New SqlCommand(strSQL, objConnection)
                cmd.Parameters.Add("@ID", SqlDbType.Int).Value = atID

                Try
                    objConnection.Open()
                    cmd.ExecuteNonQuery()
                Catch ex As Exception
                    System.Console.WriteLine(ex.ToString())
                Finally
                    objConnection.Close()
                End Try
            End If

            RadGrid.Rebind()
        End If
    End Sub


    'Show a dropdown list of the asset types in the database

    Protected Sub RadGrid_ItemDataBound(sender As Object, e As GridItemEventArgs)
        If e.Item.IsInEditMode Then
            Dim item As GridEditableItem = DirectCast(e.Item, GridEditableItem)

            If Not (TypeOf e.Item Is IGridInsertItem) Then
                Dim combo As RadComboBox = DirectCast(item.FindControl("Asset_type"), RadComboBox)

                Dim preselectedAsset As New RadComboBoxItem()
                preselectedAsset.Text = item("Asset_type").Text
                preselectedAsset.Value = item("Asset_type").Text
                combo.Items.Insert(0, preselectedAsset)
            End If
        End If
    End Sub



End Class

    <form id="form1" runat="server">
        <telerik:RadStyleSheetManager ID="RadStyleSheetManager2" runat="server"></telerik:RadStyleSheetManager>
        <telerik:RadScriptManager ID="RadScriptManager2" runat="server"></telerik:RadScriptManager>
        <telerik:RadAjaxManager ID="RadAjaxManager1" runat="server"></telerik:RadAjaxManager>
        <telerik:RadGrid ID="RadGrid" runat="server" AllowPaging="True" Width="800px"
            OnNeedDataSource="RadGrid_NeedDataSource" OnItemCommand="RadGrid_ItemCommand" onitemdatabound="RadGrid_ItemDataBound"
            OnItemCreated="RadGrid_ItemCreated" OnDeleteCommand="RadGrid_ItemDeleted" Skin="MetroTouch">
            <GroupingSettings CollapseAllTooltip="Collapse all groups"></GroupingSettings>
            <MasterTableView AutoGenerateColumns="False" CommandItemDisplay="Top" DataKeyNames="ID">
                <RowIndicatorColumn ShowNoSortIcon="False"></RowIndicatorColumn>
                <ExpandCollapseColumn ShowNoSortIcon="False"></ExpandCollapseColumn>
                <Columns>
                    <telerik:GridBoundColumn DataField="ID" DataType="System.Int32" FilterControlAltText="Filter ID column" HeaderText="ID" ReadOnly="True" SortExpression="ID" UniqueName="ID" Visible="False"></telerik:GridBoundColumn>
                    <telerik:GridBoundColumn DataField="Asset_type" FilterControlAltText="Filter Asset_type column" HeaderText="Asset_type" SortExpression="Asset_type" UniqueName="Asset_type" ></telerik:GridBoundColumn>
                    <telerik:GridBoundColumn DataField="PortalID" FilterControlAltText="Filter PortalID column" HeaderText="PortalID" SortExpression="PortalID" UniqueName="PortalID"></telerik:GridBoundColumn>
                    <telerik:GridBoundColumn DataField="asset_SN" FilterControlAltText="Filter asset_SN column" HeaderText="Serial Number" SortExpression="asset_SN" UniqueName="asset_SN"></telerik:GridBoundColumn>
                    <telerik:GridBoundColumn DataField="asset_model" FilterControlAltText="Filter asset_model column" HeaderText="Model" SortExpression="asset_model" UniqueName="asset_model"></telerik:GridBoundColumn>
                    <telerik:GridBoundColumn DataField="asset_location" FilterControlAltText="Filter asset_location column" HeaderText="Location" SortExpression="asset_location" UniqueName="asset_location"></telerik:GridBoundColumn>
                    <telerik:GridDateTimeColumn DataField="Maint_Date" FilterControlAltText="Filter Maint_Date column" HeaderText="Date of Service" SortExpression="Maint_Date" UniqueName="Maint_Date"></telerik:GridDateTimeColumn>
                    <telerik:GridBoundColumn DataField="Fill_qty" FilterControlAltText="Filter Fill_qty column" HeaderText="Fill Qty (Gallons)" SortExpression="Fill_qty" UniqueName="Fill_qty"></telerik:GridBoundColumn>
                    <telerik:GridCheckBoxColumn DataField="Active_indicator" DataType="System.Boolean" FilterControlAltText="Filter Active_indicator column" HeaderText="Active?" SortExpression="Active_indicator" UniqueName="Active_indicator"></telerik:GridCheckBoxColumn>
                    <telerik:GridBoundColumn DataField="Asset_Notes" FilterControlAltText="Filter Notes column" HeaderText="Notes" SortExpression="Asset_Notes" UniqueName="Asset_Notes"></telerik:GridBoundColumn>
                    <telerik:GridEditCommandColumn EditText="Edit" />
                    <telerik:GridButtonColumn ConfirmText="Are you sure you want to delete this record?" ConfirmDialogType="RadWindow" ConfirmTitle="Delete" CommandName="Delete" Text="Delete" />
                                  

                </Columns>
               
            </MasterTableView>
        </telerik:RadGrid>
    </form>

2 Answers, 1 is accepted

Sort by
1
Accepted
Rumen
Telerik team
answered on 09 Jul 2024, 08:52 AM

Hi Christopher,

To implement a RadComboBox with Load on Demand feature within a RadGrid, you'll need to add the RadComboBox to the grid's EditItemTemplate or InsertItemTemplate. This setup allows the RadComboBox to dynamically load items based on what the user types, pulling data as needed without loading all possible entries at once.

Here’s a step-by-step guide on how to integrate such functionality using your existing setup:

  1. Define RadComboBox in GridTemplateColumn:

    • Add a new GridTemplateColumn to your RadGrid where you want the RadComboBox to appear.
    • In the EditItemTemplate of this column, place the RadComboBox and configure it to enable Load on Demand.
  2. Configure RadComboBox:

    • Set the EnableLoadOnDemand property to True.
    • Optionally, set properties like ShowMoreResultsBox and EnableVirtualScrolling to improve usability.
    • Define the ItemsRequested event where you will handle the database querying based on the user's input.
  3. Handle ItemsRequested Event:

    • In the ItemsRequested event, write logic to query your database for items matching the text typed by the user - see this demo .
    • Bind these results back to the RadComboBox.

Here is an example of how you might define this in your ASPX page

<telerik:GridTemplateColumn UniqueName="AssetTypeColumn" HeaderText="Asset Type">
    <EditItemTemplate>
        <telerik:RadComboBox ID="RadComboBox1" runat="server" 
            EnableLoadOnDemand="True"
            ShowMoreResultsBox="true"
            EnableVirtualScrolling="true"
            OnItemsRequested="RadComboBox1_ItemsRequested">
        </telerik:RadComboBox>
    </EditItemTemplate>
</telerik:GridTemplateColumn>

And in your code-behind (C# example adapted for your VB.NET environment):
Protected Sub RadComboBox1_ItemsRequested(sender As Object, e As RadComboBoxItemsRequestedEventArgs)
    Dim combo As RadComboBox = DirectCast(sender, RadComboBox)
    Dim data As DataTable = GetData(e.Text)
    combo.DataSource = data
    combo.DataTextField = "Asset_type" ' Adjust based on your data column name
    combo.DataValueField = "Asset_type" ' Adjust based on your data column name
    combo.DataBind()
End Sub

Private Function GetData(text As String) As DataTable
    Dim dataTable As New DataTable()
    Using connection As New SqlConnection(ConfigurationManager.ConnectionStrings("YourConnectionString").ConnectionString)
        Using command As New SqlCommand("SELECT DISTINCT Asset_type FROM YourTable WHERE Asset_type LIKE @text + '%'", connection)
            command.Parameters.AddWithValue("@text", text)
            Using adapter As New SqlDataAdapter(command)
                adapter.Fill(dataTable)
            End Using
        End Using
    End Using
    Return dataTable
End Function

This setup will allow the RadComboBox within your RadGrid to dynamically load and display suggestions based on the user's input, querying the database only for relevant data. Adjust the SQL query and connection string as necessary to fit your database schema and configuration.

For more detailed information and examples, you can refer to the Telerik documentation:

 

    Best Regards,
    Rumen
    Progress Telerik

    Stay tuned by visiting our public roadmap and feedback portal pages! Or perhaps, if you are new to our Telerik family, check out our getting started resources
    cest
    Top achievements
    Rank 1
    Iron
    commented on 09 Jul 2024, 01:17 PM | edited

    So now I am having a separate issue with the radcombobox solution and maybe you can help me. When it was a textbox I had it to where if its editing or updating that it will populate the information from the database into the textbox but cant seem to get it to show into combobox as they are now a different type it seems. Additionally, I cant have them use the validation either. The line of codes being: 

     

    Dim txtSerialNum As TextBox = CType(editableItem("asset_SN").Controls(0), TextBox) 

     

    Dim assetSNEditor As GridTextBoxColumnEditor = CType(item.EditManager.GetColumnEditor("asset_SN"), GridTextBoxColumnEditor)
    AddRequiredFieldValidator(assetSNEditor.TextBoxControl, "Asset Serial Number")

     

    I tried

    Dim assetSNEditor As GridTemplateColumnEditor = CType(item.EditManager.GetColumnEditor("asset_SN"), GridTemplateColumnEditor)
    AddRequiredFieldValidator(assetSNEditor.TemplateControl, "Asset Serial Number")

     

     

    Any help more would be appreciated as it works but not anymore.

    1
    Rumen
    Telerik team
    answered on 10 Jul 2024, 07:36 AM

    Hi Christopher,

    To address the issues you are facing with populating the RadComboBox and applying validation within the RadGrid after changing from TextBox to RadComboBox, you need to handle the controls differently, e.g.

    Populating the RadComboBox in Edit Mode: Modify the RadGrid_ItemDataBound event to correctly populate the RadComboBox:

    Protected Sub RadGrid_ItemDataBound(sender As Object, e As GridItemEventArgs)
        If e.Item.IsInEditMode Then
            Dim item As GridEditableItem = DirectCast(e.Item, GridEditableItem)
            Dim combo As RadComboBox = DirectCast(item.FindControl("RadComboBox1"), RadComboBox)
    
            ' Set the selected value of the combo box
            Dim assetType As String = DataBinder.Eval(item.DataItem, "Asset_type").ToString()
            combo.Items.Insert(0, New RadComboBoxItem(assetType, assetType))
            combo.SelectedIndex = 0
        End If
    End Sub

    Applying Validation to RadComboBox: Since the RadComboBox is a different control type compared to TextBox, you need to adjust how you apply the validation. Modify the RadGrid_ItemCreated event to apply validation to the RadComboBox:

    Protected Sub RadGrid_ItemCreated(sender As Object, e As GridItemEventArgs)
        If e.Item.IsInEditMode Then
            Dim item As GridEditableItem = DirectCast(e.Item, GridEditableItem)
    
            ' For Asset_type validation
            Dim combo As RadComboBox = DirectCast(item.FindControl("RadComboBox1"), RadComboBox)
            AddRequiredFieldValidator(combo, "Asset Type")
        End If
    End Sub
    
    Private Sub AddRequiredFieldValidator(combo As RadComboBox, fieldName As String)
        Dim validator As New CustomValidator()
        validator.ID = "CustomValidator_" & fieldName.Replace(" ", "_")
        validator.ControlToValidate = combo.ID
        validator.ValidateEmptyText = True
        validator.ErrorMessage = String.Format("* {0} is required", fieldName)
        validator.ForeColor = Color.OrangeRed
        validator.ClientValidationFunction = "requiredFieldValidation"
        validator.ValidationGroup = "gridFormValidation"
        AddHandler validator.ServerValidate, AddressOf RequiredField_ServerValidate
        combo.Parent.Controls.Add(validator)
    End Sub

    Ensure you have the client-side validation function defined in your JavaScript to handle the Client-Side Validation::

    <script>
    function requiredFieldValidation(sender, args) {
        args.IsValid = args.Value.trim() !== '';
    }
    </script>

    You can check here and here for more information.

     

    Regards,
    Rumen
    Progress Telerik

    Stay tuned by visiting our public roadmap and feedback portal pages! Or perhaps, if you are new to our Telerik family, check out our getting started resources
    cest
    Top achievements
    Rank 1
    Iron
    commented on 10 Jul 2024, 07:09 PM | edited

    Very last question, I am very sorry I cant seem to pull the value of the assettype combobox as it isnt recognizing the telerik.web.ui.radcombobox. However, the RadDatePicker is fine 

     

    Code Attempted (I tried all separately)

    Dim txtAssetType As RadComboBox = TryCast(editableItem("Asset_type").FindControl("Asset_type"), RadComboBox)

    Dim txtAssetType As RadComboBox = TryCast(editableItem.FindControl("Asset_type"), RadComboBox)

    Dim txtAssetType As RadComboBox = CType(editableItem("Asset_type").Controls(0), RadComboBox)

     

    RadComboBox

     

    RadDatePicker

    Rumen
    Telerik team
    commented on 11 Jul 2024, 09:03 AM

    Here are some steps to ensure you are correctly accessing the RadComboBox:

    1. Ensure the RadComboBox Control ID Matches
    When adding the RadComboBox in the GridTemplateColumn, ensure the ID of the RadComboBox control matches the ID you are trying to find.

    2. Correctly Reference the RadComboBox
    Ensure that the ID you are using to find the RadComboBox matches the ID set in the markup.

    Here is a basic example with a dummy datasource:

    ASPX

            <telerik:RadGrid ID="RadGrid1" runat="server" AutoGenerateColumns="False" AllowPaging="True" OnNeedDataSource="RadGrid1_NeedDataSource" OnItemDataBound="RadGrid1_ItemDataBound" OnItemCommand="RadGrid1_ItemCommand">
                <MasterTableView DataKeyNames="ID" CommandItemDisplay="Top">
                    <Columns>
                        <telerik:GridBoundColumn DataField="ID" HeaderText="ID" UniqueName="ID" ReadOnly="True" Visible="False" />
                        <telerik:GridTemplateColumn UniqueName="AssetTypeColumn" HeaderText="Asset Type">
                            <EditItemTemplate>
                                <telerik:RadComboBox ID="RadComboBox1" runat="server" EnableLoadOnDemand="True" ShowMoreResultsBox="true" EnableVirtualScrolling="true" OnItemsRequested="RadComboBox1_ItemsRequested"></telerik:RadComboBox>
                            </EditItemTemplate>
                            <ItemTemplate>
                                <%# Eval("Asset_type") %>
                            </ItemTemplate>
                        </telerik:GridTemplateColumn>
                        <telerik:GridEditCommandColumn />
                        <telerik:GridButtonColumn CommandName="Delete" Text="Delete" />
                    </Columns>
                </MasterTableView>
            </telerik:RadGrid>

    ASPX.VB

        Private Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
            If Not IsPostBack Then
                RadGrid1.Rebind()
            End If
        End Sub
    
        Protected Sub RadGrid1_NeedDataSource(sender As Object, e As GridNeedDataSourceEventArgs)
            RadGrid1.DataSource = GetDummyData()
        End Sub
    
        Private Function GetDummyData() As DataTable
            Dim dataTable As New DataTable()
            dataTable.Columns.Add("ID", GetType(Integer))
            dataTable.Columns.Add("Asset_type", GetType(String))
    
            dataTable.Rows.Add(1, "Battery")
            dataTable.Rows.Add(2, "Charger")
            dataTable.Rows.Add(3, "Cable")
    
            Return dataTable
        End Function
    
        Protected Sub RadComboBox1_ItemsRequested(sender As Object, e As RadComboBoxItemsRequestedEventArgs)
            Dim combo As RadComboBox = DirectCast(sender, RadComboBox)
            Dim data As DataTable = GetComboBoxData(e.Text)
            combo.DataSource = data
            combo.DataTextField = "Asset_type"
            combo.DataValueField = "Asset_type"
            combo.DataBind()
        End Sub
    
        Private Function GetComboBoxData(text As String) As DataTable
            Dim dataTable As New DataTable()
            dataTable.Columns.Add("Asset_type", GetType(String))
    
            If text = "" Then
                dataTable.Rows.Add("Battery")
                dataTable.Rows.Add("Charger")
                dataTable.Rows.Add("Cable")
            Else
                If "Battery".StartsWith(text, StringComparison.InvariantCultureIgnoreCase) Then dataTable.Rows.Add("Battery")
                If "Charger".StartsWith(text, StringComparison.InvariantCultureIgnoreCase) Then dataTable.Rows.Add("Charger")
                If "Cable".StartsWith(text, StringComparison.InvariantCultureIgnoreCase) Then dataTable.Rows.Add("Cable")
            End If
    
            Return dataTable
        End Function
    
        Protected Sub RadGrid1_ItemDataBound(sender As Object, e As GridItemEventArgs)
            If e.Item.IsInEditMode Then
                Dim item As GridEditableItem = DirectCast(e.Item, GridEditableItem)
                Dim combo As RadComboBox = DirectCast(item.FindControl("RadComboBox1"), RadComboBox)
    
                ' Set the selected value of the combo box
                Dim assetType As String = DataBinder.Eval(item.DataItem, "Asset_type").ToString()
                combo.Items.Insert(0, New RadComboBoxItem(assetType, assetType))
                combo.SelectedIndex = 0
            End If
        End Sub
    
        Protected Sub RadGrid1_ItemCommand(sender As Object, e As GridCommandEventArgs)
            If e.CommandName = RadGrid.UpdateCommandName Or e.CommandName = RadGrid.PerformInsertCommandName Then
                If Page.IsValid Then
                    Dim editableItem As GridEditableItem = TryCast(e.Item, GridEditableItem)
    
                    ' Retrieve the RadComboBox
                    Dim combo As RadComboBox = DirectCast(editableItem.FindControl("RadComboBox1"), RadComboBox)
    
                    ' Get the selected value from RadComboBox
                    Dim assetType As String = combo.SelectedValue
    
                    ' Now use assetType as needed
                    ' For demonstration, just showing the value in a label or use it in SQL query
                    ' Dim lblMessage As Label = DirectCast(editableItem.FindControl("LblMessage"), Label)
                    ' lblMessage.Text = "Selected Asset Type: " & assetType
    
                    ' Your SQL logic here...
    
                Else
                    e.Canceled = True
                End If
            End If
        End Sub

    Common Issues and Troubleshooting
    - ID Mismatch: Ensure the IDs used in the markup and code-behind match exactly.
    - Control Not Found: If FindControl returns Nothing, the ID might be incorrect or the control might not be in the expected hierarchy.
    - Check Edit Mode: Ensure the code is being executed only when the grid item is in edit mode.

    You can check the following resources on the matter:

    Tags
    ComboBox Grid
    Asked by
    cest
    Top achievements
    Rank 1
    Iron
    Answers by
    Rumen
    Telerik team
    Share this question
    or