This is a migrated thread and some comments may be shown as answers.

RadGrid - WebUserControl - Insert/Edit not working with Sqldatasource

2 Answers 177 Views
Grid
This is a migrated thread and some comments may be shown as answers.
Vijaianand
Top achievements
Rank 1
Vijaianand asked on 21 Oct 2013, 08:06 PM
I have done this before in my other project for previous client but still struggling with it. I have similar code but edit/insert is giving "Cannot insert Null into <fieldName>" error. It works in InPlace but not in webusercontrol. It looks like the value is not getting transferred from WebUserControl form to grid for update. I have attached the code and hope to get someone to point out what am I really missing this time.

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Units.aspx.cs"
    Inherits="UMOLWeb.Views.Admin.Units" MasterPageFile="~/TopNav.Master" %>
 
<%@ MasterType VirtualPath="~/TopNav.master" %>
 
<%@ Register TagPrefix="telerik" Namespace="Telerik.Web.UI" Assembly="Telerik.Web.UI" %>
<asp:Content ID="Content1" ContentPlaceHolderID="cphHtmlHeader" runat="server">
    <style type="text/css">
        .EditFormHeader td {
            background: #25A0DA;
            padding: 10px 0px;
        }
 
        .rgRow, .rgAltRow, .rgHeader, .rtlR, .rtlA {
            font-size: small !important;
            padding: 0;
        }
 
        div.RadGrid_MetroTouch .rgHeader, div.RadGrid_MetroTouch th.rgResizeCol {
            padding-top: 0;
            padding-bottom: 0;
        }
    </style>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="cphToolbar" runat="server">
</asp:Content>
<asp:Content ID="Content3" ContentPlaceHolderID="cphContent" runat="server">
 
    <asp:Panel runat="server" Visible="false" ID="pnlContent" Style="height: 100%; margin: 0px">
        <telerik:RadScriptBlock ID="RadScriptBlock1" runat="server">
            <script type="text/javascript">
                function PopUpShowing(sender, eventArgs) {
                    var myWidth = 0, myHeight = 0;
                    if (typeof (window.innerWidth) == 'number') {
                        //Non-IE
                        myWidth = window.innerWidth;
                        myHeight = window.innerHeight;
 
                    } else if (document.documentElement && (document.documentElement.clientWidth || document.documentElement.clientHeight)) {
                        //IE 6+ in 'standards compliant mode'
                        myWidth = document.documentElement.clientWidth;
                        myHeight = document.documentElement.clientHeight;
                    } else if (document.body && (document.body.clientWidth || document.body.clientHeight)) {
                        //IE 4 compatible
                        myWidth = document.body.clientWidth;
                        myHeight = document.body.clientHeight;
                    }
 
                    popUp = eventArgs.get_popUp();
                    var gridWidth = sender.get_element().offsetWidth;
                    var gridHeight = sender.get_element().offsetHeight;
                    var popUpWidth = popUp.style.width.substr(0, popUp.style.width.indexOf("px"));
                    var popUpHeight = popUp.style.height.substr(0, popUp.style.height.indexOf("px"));
                    popUp.style.left = ((myWidth - popUpWidth) / 2 + sender.get_element().offsetLeft).toString() + "px";
                    var posy = document.body.scrollTop + document.documentElement.scrollTop;
                    popUp.style.top = (posy + sender.get_element().offsetTop + 100).toString() + "px";
                }
 
                function RowDblClick(sender, eventArgs) {
                    sender.get_masterTableView().editItem(eventArgs.get_itemIndexHierarchical());
                }
            </script>
        </telerik:RadScriptBlock>
 
        <telerik:RadAjaxManager ID="RadAjaxManager1" runat="server" DefaultLoadingPanelID="RadAjaxLoadingPanel1">
            <AjaxSettings>
                <telerik:AjaxSetting AjaxControlID="RadGrid1">
                    <UpdatedControls>
                        <telerik:AjaxUpdatedControl ControlID="RadGrid1"></telerik:AjaxUpdatedControl>
                    </UpdatedControls>
                </telerik:AjaxSetting>
            </AjaxSettings>
        </telerik:RadAjaxManager>
         <telerik:RadWindowManager ID="RadWindowManager1" runat="server"></telerik:RadWindowManager>
        <telerik:RadSplitter ID="RadSplitter1" runat="server" Width="100%" Height="100%"
            HeightOffset="175" Skin="MetroTouch" BorderSize="0">
            <telerik:RadPane ID="RadPane1" runat="server" Scrolling="Y">
                <telerik:RadGrid ID="RadGrid1" runat="server" DataSourceID="SqlDataSource1" AutoGenerateColumns="false" BorderWidth="0" AllowAutomaticUpdates="true" AllowAutomaticInserts="true"
                    DataKeyNames="ID" AllowSorting="true" Skin="Windows7" EnableTheming="false" AllowPaging="false" PagerStyle-Mode="NextPrev" PagerStyle-Position="Top" PageSize="12"
                    ShowGroupPanel="True" OnItemUpdated="RadGrid1_ItemUpdated">
                    <MasterTableView DataSourceID="SqlDataSource1" AutoGenerateColumns="False" DataKeyNames="ID"
                        CommandItemDisplay="Top" EditMode="Popup" AllowMultiColumnSorting="true" AllowAutomaticUpdates="true" AllowAutomaticInserts="true">
                        <GroupByExpressions>
                            <telerik:GridGroupByExpression>
                                <SelectFields>
                                    <telerik:GridGroupByField FieldAlias="Region" FieldName="Region"></telerik:GridGroupByField>
                                </SelectFields>
                                <GroupByFields>
                                    <telerik:GridGroupByField FieldName="Region"></telerik:GridGroupByField>
                                </GroupByFields>
                            </telerik:GridGroupByExpression>
                            <telerik:GridGroupByExpression>
                                <SelectFields>
                                    <telerik:GridGroupByField FieldAlias="BusinessUnit" FieldName="BusinessUnit"></telerik:GridGroupByField>
                                </SelectFields>
                                <GroupByFields>
                                    <telerik:GridGroupByField FieldName="BusinessUnit"></telerik:GridGroupByField>
                                </GroupByFields>
                            </telerik:GridGroupByExpression>
                            <telerik:GridGroupByExpression>
                                <SelectFields>
                                    <telerik:GridGroupByField FieldAlias="Area" FieldName="Area"></telerik:GridGroupByField>
                                </SelectFields>
                                <GroupByFields>
                                    <telerik:GridGroupByField FieldName="Area"></telerik:GridGroupByField>
                                </GroupByFields>
                            </telerik:GridGroupByExpression>
                        </GroupByExpressions>
                        <Columns>
                            <telerik:GridEditCommandColumn ButtonType="ImageButton" HeaderText="Edit">
                            </telerik:GridEditCommandColumn>
                            <telerik:GridBoundColumn DataField="UnitNo" HeaderText="Unit" SortExpression="UnitNo"
                                UniqueName="UnitNo">
                            </telerik:GridBoundColumn>
                            <telerik:GridBoundColumn DataField="UnitType" HeaderText="UnitType" SortExpression="UnitType"
                                UniqueName="UnitType">
                            </telerik:GridBoundColumn>
                            <telerik:GridBoundColumn DataField="HorsePower" HeaderText="FERCHP" SortExpression="HorsePower"
                                UniqueName="HorsePower">
                            </telerik:GridBoundColumn>
                            <telerik:GridBoundColumn DataField="Engine" HeaderText="Engine" SortExpression="Engine"
                                UniqueName="Engine">
                            </telerik:GridBoundColumn>
                            <telerik:GridBoundColumn DataField="Region" HeaderText="Region" SortExpression="Region"
                                UniqueName="Region">
                            </telerik:GridBoundColumn>
                            <telerik:GridBoundColumn DataField="BusinessUnit" HeaderText="BU" SortExpression="BusinessUnit"
                                UniqueName="BusinessUnit">
                            </telerik:GridBoundColumn>
                            <telerik:GridBoundColumn DataField="Area" HeaderText="Area" SortExpression="Area"
                                UniqueName="Area">
                            </telerik:GridBoundColumn>
                            <telerik:GridBoundColumn DataField="Station" HeaderText="Station" SortExpression="Station"
                                UniqueName="Station">
                            </telerik:GridBoundColumn>
                            <telerik:GridCheckBoxColumn DataField="IsActive" DataType="System.Boolean" HeaderText="Active" runat="server"></telerik:GridCheckBoxColumn>
                        </Columns>
                        <EditFormSettings CaptionDataField="UnitNo" CaptionFormatString="Edit Information for Unit: {0}"
                            EditFormType="WebUserControl" UserControlName="~/Views/Controls/EditUnitDetails.ascx" InsertCaption="New Unit">
                            <FormTableItemStyle Wrap="False" Width="400px"></FormTableItemStyle>
                            <FormCaptionStyle CssClass="EditFormHeader"></FormCaptionStyle>
                            <FormMainTableStyle GridLines="None" CellSpacing="1" CellPadding="3" />
                            <FormTableStyle CellSpacing="0" CellPadding="2" Height="150px" />
                            <EditColumn ButtonType="ImageButton" InsertText="Insert Location" UpdateText="Update record"
                                UniqueName="EditCommandColumn1" CancelText="Cancel edit">
                            </EditColumn>
                            <FormTableButtonRowStyle HorizontalAlign="Left" CssClass="EditFormButtonRow"></FormTableButtonRowStyle>
                        </EditFormSettings>
                    </MasterTableView>
                    <ClientSettings AllowGroupExpandCollapse="True" AllowDragToGroup="True">
                        <ClientEvents OnPopUpShowing="PopUpShowing" />
                        <ClientEvents OnRowDblClick="RowDblClick" />
                    </ClientSettings>
                    <GroupingSettings ShowUnGroupButton="true"></GroupingSettings>
                </telerik:RadGrid>
            </telerik:RadPane>
        </telerik:RadSplitter>
        <telerik:RadAjaxLoadingPanel ID="RadAjaxLoadingPanel1" runat="server" Skin="Windows7">
        </telerik:RadAjaxLoadingPanel>
    </asp:Panel>
    <asp:Panel ID="pnlError" runat="server" Visible="false">
        <table>
            <tr>
                <td style="color: red; font-weight: bold">
                    <asp:Label runat="server" ID="lblError"></asp:Label></td>
            </tr>
        </table>
    </asp:Panel>
 
    <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:WebAppConnectionString %>"
        SelectCommand="SELECT U.ID,UnitNo, UnitType, EngineType, Model, Manufacturer, HorsePower, CSLocation, UsedforUnitMaintenance, Region, BusinessUnit,Area, Station, CASE WHEN U.[IsActive] =1 THEN 'true' Else 'false' END AS IsActive, LocationId FROM Units U INNER JOIN Location L ON LocationId = L.Id ORDER BY Region, BusinessUnit, Area, Station"
        UpdateCommand="UPDATE Units SET [UnitNo] = @UnitNo, [UnitType] = @UnitType, [EngineType] = @EngineType, [Model] = @Model, [Manufacturer] = @Manufacturer, [HorsePower] = @HorsePower, [CSLocation] = @CSLocation, [UsedforUnitMaintenance] = @UsedforUnitMaintenance, [LocationId] = @LocationId, IsActive=@IsActive WHERE [ID] = @ID">
        <InsertParameters>
            <asp:Parameter Name="UnitNo" Type="String" />
            <asp:Parameter Name="UnitType" Type="String" />
            <asp:Parameter Name="EngineType" Type="String" />
            <asp:Parameter Name="Model" Type="String" />
            <asp:Parameter Name="Manufacturer" Type="String" />
            <asp:Parameter Name="HorsePower" Type="Int32" />
            <asp:Parameter Name="CSLocation" Type="Boolean" />
            <asp:Parameter Name="UsedforUnitMaintenance" Type="Boolean" />
            <asp:Parameter Name="LocationId" Type="Int16"/>
            <asp:Parameter Name="IsActive" Type="Boolean" />
        </InsertParameters>
        <UpdateParameters>
            <asp:Parameter Name="UnitNo" Type="String" />
            <asp:Parameter Name="UnitType" Type="String" />
            <asp:Parameter Name="EngineType" Type="String" />
            <asp:Parameter Name="Model" Type="String" />
            <asp:Parameter Name="Manufacturer" Type="String" />
            <asp:Parameter Name="HorsePower" Type="String" />
            <asp:Parameter Name="CSLocation" Type="Boolean" />
            <asp:Parameter Name="UsedforUnitMaintenance" Type="Boolean" />
            <asp:Parameter Name="LocationId" Type="Int16" />
            <asp:Parameter Name="IsActive" Type="Boolean" />
            <asp:Parameter Name="Id" Type="Int16" />
        </UpdateParameters>
    </asp:SqlDataSource>
</asp:Content>


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Security;
using System.Text;
 
namespace UMOLWeb.Views.Admin
{
    public partial class Units : System.Web.UI.Page
    {
        public string PAGE_FUNCTION = "Units Information";
        const string PAGE_DESCRIPTION = "Adit/Edit Location, Unit and Task Information";
 
        private string gridMessage = null;
 
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Roles.IsUserInRole("Manager") && Roles.IsUserInRole("ITSupport"))
            {
                pnlContent.Visible = true;
            }
            else
            {
                lblError.Text = "You are not authorized to view this page";
                pnlError.Visible = true;
            }
        }
 
       
 
        protected void RadGrid1_ItemUpdated(object sender, Telerik.Web.UI.GridUpdatedEventArgs e)
        {
            // Show messages on Update
            if ((e.Exception != null))
            {
                e.ExceptionHandled = true;
                e.KeepInEditMode = true;
                var aMsg = e.Exception.Message.ToString().Split(';');
                SetMessage("<b>Record cannot be updated</b>.<br />Reason:" + String.Format("<span style='color:red'>" + aMsg[0] + "</span>"));
            }
            else
            {
                SetMessage("Record is Updated!");
            }
        }
 
        private void SetMessage(string message)
        {
            gridMessage = message.Replace("'", "\\'").Replace("\n", "<br />");
        }
 
        private void DisplayMessage(string text)
        {
            //Show the error message on the RadWindow
            string msg = "radalert('" + gridMessage + "',500,100);";
            RadAjaxManager1.ResponseScripts.Add(msg);
        }
        #region "Master Page Settings"
 
        protected void Page_PreRender(object sender, System.EventArgs e)
        {
            var _m = Master;
            _m.PageFunction = PAGE_FUNCTION;
            _m.PageDescription = PAGE_DESCRIPTION;
 
            if (!(String.IsNullOrEmpty(gridMessage)))
                DisplayMessage(gridMessage);
        }
 
        #endregion
    }
}

<%@ Control Language="C#" CodeBehind="EditUnitDetails.ascx.cs" Inherits="UMOLWeb.Views.Controls.EditUnitDetails" %>
<%@ Register Assembly="Telerik.Web.UI" Namespace="Telerik.Web.UI" TagPrefix="telerik" %>
<table>
    <tr>
        <td>Location:
        </td>
        <td>
            <telerik:RadComboBox DataTextField="Location" DropDownAutoWidth="Enabled" DataValueField="Id" DataSourceID="sqlDataSrc1"
                 ShowMoreResultsBox="true"  Width="300px" EnableLoadOnDemand="true"
                UniqueName="Location" Filter="Contains" AutoPostBack="true" ID="LocationId"
                ItemsPerRequest="10" runat="server">
 
            </telerik:RadComboBox>
        </td>
    </tr>
    <tr>
        <td>Unit No:
        </td>
        <td>
            <asp:TextBox runat="server" ID="UnitNo" Text='<%# DataBinder.Eval(DataItem, "UnitNo")%>'></asp:TextBox>
        </td>
    </tr>
    <tr>
        <td>Unit Type:
        </td>
        <td>
            <asp:TextBox runat="server" ID="UnitType" Text='<%# DataBinder.Eval(DataItem, "UnitType")%>'></asp:TextBox>
        </td>
    </tr>
    <tr>
        <td>Engine Type:
        </td>
        <td>
            <asp:TextBox runat="server" ID="EngineType" Text='<%# DataBinder.Eval(DataItem, "EngineType")%>'></asp:TextBox>
        </td>
    </tr>
    <tr>
        <td>Manufacturer:
        </td>
        <td>
            <asp:TextBox runat="server" ID="Manufacturer" Text='<%# DataBinder.Eval(DataItem, "Manufacturer")%>'></asp:TextBox>
        </td>
    </tr>
    <tr>
        <td>Model:
        </td>
        <td>
            <asp:TextBox runat="server" ID="Model" Text='<%# DataBinder.Eval(DataItem, "Model")%>'></asp:TextBox>
        </td>
    </tr>
    <tr>
        <td>HorsePower:
        </td>
        <td>
            <asp:TextBox runat="server" ID="HorsePower" Text='<%# DataBinder.Eval(DataItem, "HorsePower")%>'></asp:TextBox>
        </td>
    </tr>
    <tr>
        <td>CS Location:
        </td>
        <td>
            <asp:CheckBox runat="server" ID="CSLocation" Checked='<%# DataBinder.Eval(DataItem, "CSLocation")%>' />
        </td>
    </tr>
    <tr>
        <td>Used for Maintenance:
        </td>
        <td>
            <asp:CheckBox runat="server" ID="UsedforUnitMaintenance" Checked='<%# DataBinder.Eval(DataItem, "UsedforUnitMaintenance")%>' />
        </td>
    </tr>
     <tr>
        <td>Active:
        </td>
        <td>
            <asp:CheckBox runat="server" ID="IsActive" Checked='<%# Convert.ToBoolean(DataBinder.Eval(DataItem, "IsActive"))%>' />
        </td>
    </tr>
 
    <tr>
        <td>
            <div class="Form_Buttons">
                <asp:LinkButton ID="btnSave" runat="server" Text="Save" CommandName="Update" Visible='<%# !(DataItem is Telerik.Web.UI.GridInsertionObject) %>' /> 
                <asp:LinkButton ID="btnAdd" runat="server" Text="Insert" CommandName="PerformInsert"
                    Visible='<%# (DataItem is Telerik.Web.UI.GridInsertionObject) %>' /> 
                <asp:LinkButton ID="btnCancel" runat="server" Text="Cancel" CausesValidation="false"
                    CommandName="Cancel" />
            </div>
        </td>
    </tr>
</table>
<asp:SqlDataSource ID="sqlDataSrc1" runat="server" ConnectionString="<%$ ConnectionStrings:WebAppConnectionString %>"
    SelectCommand="SELECT Region + '-' + BusinessUnit + '-' + Area + '-' + Station AS 'Location', Id FROM [Location]"></asp:SqlDataSource>
<asp:SqlDataSource ID="sqlDataSrc2" runat="server" ConnectionString="<%$ ConnectionStrings:WebAppConnectionString %>"></asp:SqlDataSource>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections.Specialized;
using System.Data;
using Telerik.Web.UI;
using UMOLWeb.Shared;
using UMOLWeb.Models;
 
namespace UMOLWeb.Views.Controls
{
    #region "events"
    public partial class EditUnitDetails : System.Web.UI.UserControl, IBindableControl
    {
        private object _dataItem = null;
 
        public object DataItem
        {
            get{return this._dataItem;}
            set{this._dataItem = value;}
        }
 
        protected void Page_Load(object sender, EventArgs e)
        {
             
        }
 
        protected void Page_PreRender(object sender, EventArgs e)
        {
            if (!(DataItem is Telerik.Web.UI.GridInsertionObject))
            {
                DataRowView drv = (DataRowView)_dataItem;
 
                if (drv != null)
                {
                    RadComboBoxItem loc = new RadComboBoxItem();
                    loc.Text = drv.Row["Region"].ToString() + "-" + drv.Row["BusinessUnit"].ToString() + "-" + drv.Row["Area"].ToString() + "-" + drv.Row["Station"].ToString();
                    loc.Value = drv.Row["LocationId"].ToString();
                    LocationId.Items.Add(loc);
                    loc.Selected = true;
                    loc.DataBind();
                }
            }
        }
 
       
 
 
        void IBindableControl.ExtractValues(IOrderedDictionary Dictionary)
        {
 
            try
            {
                //retrives all Textbox and add thier values to the dictionary
                foreach (object ctrl in Controls)
                {
                    if ((ctrl is TextBox))
                    {
                        //    //OfType<TextBox>().Select(control => new { FieldName = control.ID, FieldValue = control.Text }))
                        Dictionary.Add(((TextBox)ctrl).ID, ((TextBox)ctrl).Text);
                    }
 
                    if (ctrl is RadComboBox)
                    {
                        Dictionary.Add(((RadComboBox)ctrl).ID, ((RadComboBox)ctrl).SelectedValue);
                    }
 
                    if (ctrl is CheckBox)
                    {
                        Dictionary.Add(((CheckBox)ctrl).ID, ((CheckBox)ctrl).Checked);
                    }
                }
 
            }
            catch (Exception ex)
            {
            }
        }
 
 
    #endregion
}
}


It is not going to extractvalue method at all. 

2 Answers, 1 is accepted

Sort by
0
Konstantin Dikov
Telerik team
answered on 24 Oct 2013, 01:37 PM
Hi Vijaianand,

Could you please refer to the following online demo for Edit/Insert with user controls as edit form:

Additional information for Custom Edit Forms could be found in this help article.

As you will see from the demo and from the help article, the user control should inherit only System.Web.UI.UserControl class and different approach should be used to bind the data. 

If further assistance is needed, please do not hesitate to get back to us.

 

Regards,
Konstantin Dikov
Telerik
If you want to get updates on new releases, tips and tricks and sneak peeks at our product labs directly from the developers working on the RadControls for ASP.NET AJAX, subscribe to the blog feed now.
0
Vijaianand
Top achievements
Rank 1
answered on 28 Oct 2013, 08:45 PM
I went through it one more time and referred my previous projects. I was bit confused and now got it right.

As it mentioned, editform with usercontrol cannot be handled using extravalues() and no automatic update/delete happens. We gotta do it manually. So I finally tapped into the RadGrid UpdateCommand and took care of it manually. 

Thanks
Tags
Grid
Asked by
Vijaianand
Top achievements
Rank 1
Answers by
Konstantin Dikov
Telerik team
Vijaianand
Top achievements
Rank 1
Share this question
or