RadDropDownList Bind data from different table and save it to another table

3 posts, 0 answers
  1. Raihan
    Raihan avatar
    2 posts
    Member since:
    Jul 2019

    Posted 17 Dec 2019 Link to this post

    Hi,

    i am trying to pull up data into RadDropDownList on EditItemTemplate from Vendors Table which has two columns VendorID and VendorName. But this RadGrid datasouce bound to anther table which is ItemDescription table with multiple columns along with VendorID and VendorName. All i am looking for when user will add the item in the grid, popup vendors name and give them ability to select and save it to ItemDescription table and when they will edit the existing item display vendor name as read only.

    Note: i was able to pull up data from vendors Table and save only VendorId into ItemDescription table, not VendorName though

    Thanks in advanced!

  2. Raihan
    Raihan avatar
    2 posts
    Member since:
    Jul 2019

    Posted 17 Dec 2019 Link to this post

    using below markup:
    <telerik:RadGrid RenderMode="Lightweight" ID="RadGrid1" runat="server" DataSourceID="EntityDataSourceSchedule"
                AllowPaging="True" AllowAutomaticUpdates="True" AllowAutomaticInserts="True"
                AllowAutomaticDeletes="True" AllowSorting="True" OnItemCreated="RadGrid1_ItemCreated"
                OnItemInserted="RadGrid1_ItemInserted" OnPreRender="RadGrid1_PreRender" OnInsertCommand="RadGrid1_InsertCommand" AllowFilteringByColumn="True" CellSpacing="-1" GridLines="Both">
                <PagerStyle Mode="NextPrevAndNumeric" />
                <GroupingSettings CollapseAllTooltip="Collapse all groups"></GroupingSettings>
                <ExportSettings ExportOnlyData="true" IgnorePaging="true"></ExportSettings>
                <MasterTableView DataSourceID="EntityDataSourceSchedule" AutoGenerateColumns="False"
                    AllowFilteringByColumn="true" TableLayout="Auto" CommandItemDisplay="Top"
                    InsertItemPageIndexAction="ShowItemOnFirstPage" DataKeyNames="ITEM_DESCRIPTION">
                    <CommandItemSettings ShowExportToCsvButton="true" ShowExportToExcelButton="true" ShowExportToPdfButton="true" ShowExportToWordButton="true" />
                    <Columns>
                        <telerik:GridEditCommandColumn UniqueName="EditCommandColumn">
                        </telerik:GridEditCommandColumn>
                        <telerik:GridTemplateColumn HeaderText="VENDOR NAME" Visible="false" SortExpression="VENDOR_DESCR" UniqueName="VENDOR_ID">
                            <%--<ItemTemplate>
                                <%# Eval("VENDOR_ID")%>
                            </ItemTemplate>--%>
                            <EditItemTemplate>
                                <telerik:RadDropDownList ID="rddl_Vendors" runat="server"  DataSourceID="EntityDataSourceVendor" SelectedValue='<%# Bind("VENDOR_ID","VENDOR_DESCRIPTION") %>' EnableInsert="True" EnableUpdate="True" DataTextField="VENDOR_DESCRIPTION" DataValueField="VENDOR_ID" AppendDataBoundItems="true">
                                    <%--<ItemTemplate>
                                         <%# Eval("VENDOR_DESCR")%>
                                    </ItemTemplate>--%>
                                </telerik:RadDropDownList>
                            </EditItemTemplate>
                            <FilterTemplate>
                                <telerik:RadDropDownList runat="server" ID="ddlProcessUnitCatFilter" AppendDataBoundItems="true">
                                </telerik:RadDropDownList>
                            </FilterTemplate>
                        </telerik:GridTemplateColumn>
  3. Attila Antal
    Admin
    Attila Antal avatar
    609 posts

    Posted 20 Dec 2019 Link to this post

    Hi Rakibo,

    Decide which value of the DropDownList would you like to update after selecting and bind that to the Column. There is Text and Value for a DropDownList. If you want to save the Text, you'll need to bind the SelectedText property, or if you want the Value, Bind the SelectedValue like you did in your example.

    <telerik:GridTemplateColumn HeaderText="VENDOR NAME" Visible="false" SortExpression="VENDOR_DESCR" UniqueName="VENDOR_ID">
        <ItemTemplate>
            <%# Eval("ShipCountry")%>
        </ItemTemplate>
        <EditItemTemplate>
            <telerik:RadDropDownList ID="rddl_Vendors" runat="server"
                OnDataBinding="rddl_Vendors_DataBinding"
                SelectedText='<%# Bind("ShipCountry") %>'
                DataTextField="ShipCountry"
                DataValueField="OrderID">
            </telerik:RadDropDownList>
        </EditItemTemplate>
    </telerik:GridTemplateColumn>

     

    Here is a complete example that you can try:

    <asp:Label ID="Label1" runat="server" Text="Action:"></asp:Label>
    <telerik:RadGrid ID="RadGrid1" runat="server" AllowPaging="True" Width="800px"
        AutoGenerateEditColumn="true"
        AutoGenerateDeleteColumn="true"
        OnNeedDataSource="RadGrid1_NeedDataSource"
        OnInsertCommand="RadGrid1_InsertCommand"
        OnUpdateCommand="RadGrid1_UpdateCommand"
        OnDeleteCommand="RadGrid1_DeleteCommand">
    
        <MasterTableView AutoGenerateColumns="False" DataKeyNames="OrderID" CommandItemDisplay="Top" InsertItemDisplay="Top" InsertItemPageIndexAction="ShowItemOnLastPage">
            <Columns>
                <telerik:GridBoundColumn DataField="OrderID" DataType="System.Int32"
                    FilterControlAltText="Filter OrderID column" HeaderText="OrderID"
                    ReadOnly="True" SortExpression="OrderID" UniqueName="OrderID">
                </telerik:GridBoundColumn>
                <telerik:GridDateTimeColumn DataField="OrderDate" DataType="System.DateTime"
                    FilterControlAltText="Filter OrderDate column" HeaderText="OrderDate"
                    SortExpression="OrderDate" UniqueName="OrderDate">
                </telerik:GridDateTimeColumn>
                <telerik:GridNumericColumn DataField="Freight" DataType="System.Decimal"
                    FilterControlAltText="Filter Freight column" HeaderText="Freight"
                    SortExpression="Freight" UniqueName="Freight">
                </telerik:GridNumericColumn>
                <telerik:GridBoundColumn DataField="ShipName"
                    FilterControlAltText="Filter ShipName column" HeaderText="ShipName"
                    SortExpression="ShipName" UniqueName="ShipName">
                </telerik:GridBoundColumn>
                <telerik:GridBoundColumn DataField="ShipCountry" ReadOnly="true"
                    FilterControlAltText="Filter ShipCountry column" HeaderText="ShipCountry"
                    SortExpression="ShipCountry" UniqueName="ShipCountry">
                </telerik:GridBoundColumn>
                <telerik:GridTemplateColumn HeaderText="VENDOR NAME" Visible="false" SortExpression="VENDOR_DESCR" UniqueName="VENDOR_ID">
                    <ItemTemplate>
                        <%# Eval("ShipCountry")%>
                    </ItemTemplate>
                    <EditItemTemplate>
                        <telerik:RadDropDownList ID="rddl_Vendors" runat="server"
                            OnDataBinding="rddl_Vendors_DataBinding"
                            SelectedText='<%# Bind("ShipCountry") %>'
                            DataTextField="ShipCountry"
                            DataValueField="OrderID">
                        </telerik:RadDropDownList>
                    </EditItemTemplate>
                </telerik:GridTemplateColumn>
            </Columns>
        </MasterTableView>
    </telerik:RadGrid>

     

    C# - Code behind

    #region Properties for CRUD Operations
    public DataTable SessionDataSource
    {
        get
        {
            string sessionKey = "SessionDataSource";
    
            if (Session[sessionKey] == null || !IsPostBack)
            {
                Session[sessionKey] = OrdersTable();
            }
            return (DataTable)Session[sessionKey];
        }
    }
    #endregion
    
    #region RadGrid Events for CRUD Operations
    
    // CREATE (Add New Record)
    protected void RadGrid1_InsertCommand(object sender, GridCommandEventArgs e)
    {
        GridEditableItem editedItem = e.Item as GridEditableItem;
    
        DataRow newRow = SessionDataSource.NewRow();
    
        //As this example demonstrates only in-memory editing, a new primary key value should be generated
        //This should not be applied when updating directly the database
        DataRow[] allValues = SessionDataSource.Select("OrderID = MAX(OrderID)");
    
        if (allValues.Length > 0)
        {
            newRow["OrderID"] = int.Parse(allValues[0]["OrderID"].ToString()) + 1;
        }
        else
        {
            newRow["OrderID"] = 1; //the table is empty;
        }
    
        //Set new values
        Hashtable newValues = new Hashtable();
        //The GridTableView will fill the values from all editable columns in the hash
        e.Item.OwnerTableView.ExtractValuesFromItem(newValues, editedItem);
    
        try
        {
            foreach (DictionaryEntry entry in newValues)
            {
                newRow[(string)entry.Key] = entry.Value;
            }
        }
        catch (Exception ex)
        {
            Label1.Text += string.Format("<br />Unable to insert into Orders. Reason: {0}", ex.Message);
            e.Canceled = true;
            return;
        }
    
        SessionDataSource.Rows.Add(newRow);
        //Code for updating the database ca go here...
        Label1.Text += string.Format("<br />Order {0} inserted", newRow["OrderID"]);
    }
    
    // READ (data binding)
    protected void RadGrid1_NeedDataSource(object sender, GridNeedDataSourceEventArgs e)
    {
        RadGrid1.DataSource = SessionDataSource;
    }
    
    // UPDATE
    protected void RadGrid1_UpdateCommand(object sender, GridCommandEventArgs e)
    {
        GridEditableItem editedItem = e.Item as GridEditableItem;
    
        //Locate the changed row in the DataSource
        DataRow[] changedRows = SessionDataSource.Select(string.Format("OrderID = {0}", editedItem.GetDataKeyValue("OrderID")));
    
        if (changedRows.Length != 1)
        {
            this.Label1.Text += "Unable to locate the Order for updating.";
            e.Canceled = true;
            return;
        }
        //Update new values
        Hashtable newValues = new Hashtable();
        e.Item.OwnerTableView.ExtractValuesFromItem(newValues, editedItem);
        changedRows[0].BeginEdit();
        try
        {
            foreach (DictionaryEntry entry in newValues)
            {
                changedRows[0][(string)entry.Key] = entry.Value;
            }
            changedRows[0].EndEdit();
        }
        catch (Exception ex)
        {
            changedRows[0].CancelEdit();
            Label1.Text += string.Format("Unable to update Orders. Reason: {0}", ex.Message);
            e.Canceled = true;
            return;
        }
    }
    
    // DELETE
    protected void RadGrid1_DeleteCommand(object sender, GridCommandEventArgs e)
    {
        GridDataItem dataItem = e.Item as GridDataItem;
        string ID = dataItem.GetDataKeyValue("OrderID").ToString();
    
        if (SessionDataSource.Rows.Find(ID) != null)
        {
            SessionDataSource.Rows.Find(ID).Delete();
        }
    }
    #endregion
    
    #region DataSource
    private DataTable OrdersTable()
    {
        DataTable dt = new DataTable();
    
        dt.Columns.Add(new DataColumn("OrderID", typeof(int)));
        dt.Columns.Add(new DataColumn("OrderDate", typeof(DateTime)));
        dt.Columns.Add(new DataColumn("Freight", typeof(decimal)));
        dt.Columns.Add(new DataColumn("ShipName", typeof(string)));
        dt.Columns.Add(new DataColumn("ShipCountry", typeof(string)));
    
        dt.PrimaryKey = new DataColumn[] { dt.Columns["OrderID"] };
    
        for (int i = 0; i < 70; i++)
        {
            int index = i + 1;
    
            DataRow row = dt.NewRow();
    
            row["OrderID"] = index;
            row["OrderDate"] = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 0, 0, 0).AddHours(index);
            row["Freight"] = index * 0.1 + index * 0.01;
            row["ShipName"] = "Name " + index;
            row["ShipCountry"] = "Country " + index;
    
            dt.Rows.Add(row);
        }
    
        return dt;
    }
    #endregion
    
    protected void rddl_Vendors_DataBinding(object sender, EventArgs e)
    {
        var rddl = (RadDropDownList)sender;
        rddl.DataSource = OrdersTable();
    }

     

    Kind regards,
    Attila Antal
    Progress Telerik

    Get quickly onboarded and successful with your Telerik and/or Kendo UI products with the Virtual Classroom free technical training, available to all active customers. Learn More.
Back to Top