Drag and Drop from Grid

5 posts, 0 answers
  1. Clark
    Clark avatar
    26 posts
    Member since:
    Jan 2011

    Posted 18 Jul 2011 Link to this post

    I am trying to get the Demo code working in my project with the Grid / Scheduler drag and drop demo and I am getting an error from the java-script function rowDropping. This line is throwing the error:

    $get("TargetSlotHiddenField").value = timeSlot.get_index();

    The error I get is: "Microsoft JScript runtime error: Unable to set value of the property 'value' : object is null or undefined"

    I am not sure what I am missing, I have looked through the demo code several times.

    Thanks!
    Clark

  2. Clark
    Clark avatar
    26 posts
    Member since:
    Jan 2011

    Posted 19 Jul 2011 Link to this post

    I fixed this issue and now I am not getting any errors but it still doesn't show the row in the scheduler. I have debugged it several times and have no idea where to look now.

    Markup
    -----------------

    <%@ Page Title="" Language="C#" MasterPageFile="~/RM.Master" AutoEventWireup="true" CodeBehind="Dispatch.aspx.cs" Inherits="RM.Dispatch" %>
    <%@ Register assembly="Telerik.Web.UI" namespace="Telerik.Web.UI" tagprefix="telerik" %>
    <asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
     
    <table width="900px">
    <tr>
    <td>
        <telerik:RadScriptManager ID="RadScriptManager1" Runat="server">
        </telerik:RadScriptManager>
           <telerik:RadScriptBlock ID="RadScriptBlock1" runat="server">
     
            <script type="text/javascript">
     
     
                function rowDropping(sender, eventArgs) {
                    // Fired when the user drops a grid row
                    var htmlElement = eventArgs.get_destinationHtmlElement();
                    var scheduler = $find('<%= rsService.ClientID %>');
     
                    if (isPartOfSchedulerAppointmentArea(htmlElement)) {
                        // The row was dropped over the scheduler appointment area
                        // Find the exact time slot and save its unique index in the hidden field
                        var timeSlot = scheduler._activeModel.getTimeSlotFromDomElement(htmlElement);
     
                        $get("ctl00$ContentPlaceHolder1$TargetSlotHiddenField").value = timeSlot.get_index();
     
                        // The HTML needs to be set in order for the postback to execute normally
                        eventArgs.set_destinationHtmlElement("TargetSlotHiddenField");
                    }
                    else {
                        // The node was dropped elsewhere on the document
                        eventArgs.set_cancel(true);
                    }
                }
     
                function isPartOfSchedulerAppointmentArea(htmlElement) {
                    // Determines if an html element is part of the scheduler appointment area
                    // This can be either the rsContent or the rsAllDay div (in day and week view)
                    return $telerik.$(htmlElement).parents().is("div.rsAllDay") ||
                                $telerik.$(htmlElement).parents().is("div.rsContent")
                }
     
                function onRowDoubleClick(sender, args) {
                    sender.get_masterTableView().editItem(args.get_itemIndexHierarchical());
                }
            </script>
     
        </telerik:RadScriptBlock>
        <!-- TODO / Add appoiontment Id to rmSO table -->
        <input type="hidden" runat="server" id="TargetSlotHiddenField" />
        <asp:SqlDataSource ID="GridDS" runat="server"
            ConnectionString="<%$ ConnectionStrings:RMConnectionString %>"
            SelectCommand="SELECT [SONumber],[AppointmentID], [Address1], [State], [Zip], [Subject], [Description], [City] FROM [rmSO]">
        </asp:SqlDataSource>
        <asp:SqlDataSource ID="SchedulerDS" runat="server"
            ConnectionString="<%$ ConnectionStrings:RMConnectionString %>"
            SelectCommand="SELECT [AppointmentID], [Start], [End], [Subject], [Due], [Priority] FROM [rmScheduler] WHERE ([Start] IS NOT NULL) AND ([End] IS NOT NULL)"
            InsertCommand="INSERT INTO [rmScheduler] ([Subject],[AppointmentID], [Start], [End]) VALUES (@Subject, @AppointmentID,@Start, @End)"
            UpdateCommand="UPDATE [rmScheduler] SET [Start] = @Start, [End] = @End, [Subject] = @Subject WHERE AppointmentID = @AppointmentID"
            DeleteCommand="DELETE FROM [rmScheduler] WHERE [AppointmentID] = @AppointmentID">
            <insertparameters>
                    <asp:Parameter Name="Subject" Type="String" />
                    <asp:Parameter Name="AppointmentID" Type="Int32" />
                    <asp:Parameter Name="Start" Type="DateTime" />
                    <asp:Parameter Name="End" Type="DateTime" />
                </insertparameters>
            <updateparameters>
                    <asp:Parameter Name="Subject" Type="String" />
                    <asp:Parameter Name="Start" Type="DateTime" />
                    <asp:Parameter Name="End" Type="DateTime" />
                    <asp:Parameter Name="AppointmentID" Type="Int32" />
                </updateparameters>
            <deleteparameters>
                    <asp:Parameter Name="AppointmentID" Type="Int32" />
                </deleteparameters>
                </asp:SqlDataSource>
        <telerik:RadAjaxManager runat="server" ID="RadAjaxManager1">
            <ajaxsettings>
                    <telerik:AjaxSetting AjaxControlID="rsService">
                        <UpdatedControls>
                            <telerik:AjaxUpdatedControl ControlID="rsService" />
                        </UpdatedControls>
                    </telerik:AjaxSetting>
                    <telerik:AjaxSetting AjaxControlID="rgService">
                        <UpdatedControls>
                            <telerik:AjaxUpdatedControl ControlID="rgService" />
                        </UpdatedControls>
                    </telerik:AjaxSetting>
                </ajaxsettings>
        </telerik:RadAjaxManager>
        </td>
    </tr>
    <tr>
    <td>
        <telerik:RadScheduler ID="rsService" DataSourceID="SchedulerDS" runat="server" DataKeyField="AppointmentID" DataStartField="Start" DataEndField="End"
                       DataSubjectField="Subject" CustomAttributeNames="Due, Priority" Skin="Black"
                        OnAppointmentCommand="rsService_AppointmentCommand" OnAppointmentInsert="rsService_AppointmentInsert">
                    <TimeSlotContextMenuSettings EnableDefault="true" />
         <AppointmentContextMenuSettings EnableDefault="true" />
        </telerik:RadScheduler>
    </td>
    </tr>
    <tr>
    <td>
    <div style="margin-left: 56px; border: none;">
        <telerik:RadGrid ID="rgService" runat="server" Skin="Black" AllowPaging="True"  OnRowDrop="rgService_RowDrop"
            DataSourceID="GridDS" GridLines="None"
             AllowAutomaticInserts="True" AllowAutomaticUpdates="true"
                        ShowFooter="true" OnItemCreated="rgService_ItemCreated" OnItemCommand="rgService_ItemCommand"
                         AllowSorting="true">
                            <clientsettings allowrowsdragdrop="True">
                                <Selecting AllowRowSelect="True" />
                                <ClientEvents OnRowDropping="rowDropping" OnRowDblClick="onRowDoubleClick" />
                            </clientsettings>
    <MasterTableView AutoGenerateColumns="False" datakeynames="AppointmentID" insertitemdisplay="Bottom" editmode="InPlace"
                DataSourceID="GridDS">
    <RowIndicatorColumn>
    <HeaderStyle Width="20px"></HeaderStyle>
    </RowIndicatorColumn>
     
    <ExpandCollapseColumn>
    <HeaderStyle Width="20px"></HeaderStyle>
    </ExpandCollapseColumn>
        <Columns>
        <telerik:GridBoundColumn DataField="AppointmentID" DataType="System.Int32"
                HeaderText="AppointmentID" ReadOnly="True" SortExpression="AppointmentID"
                UniqueName="AppointmentID">
            </telerik:GridBoundColumn>
            <telerik:GridBoundColumn DataField="SONumber" DataType="System.Int32"
                HeaderText="SONumber" ReadOnly="True" SortExpression="SONumber"
                UniqueName="SONumber">
            </telerik:GridBoundColumn>
            <telerik:GridBoundColumn DataField="Address1" HeaderText="Address1"
                SortExpression="Address1" UniqueName="Address1">
            </telerik:GridBoundColumn>
            <telerik:GridBoundColumn DataField="State" HeaderText="State"
                SortExpression="State" UniqueName="State">
            </telerik:GridBoundColumn>
            <telerik:GridBoundColumn DataField="Zip" HeaderText="Zip" SortExpression="Zip"
                UniqueName="Zip">
            </telerik:GridBoundColumn>
              <telerik:GridBoundColumn DataField="Subject" HeaderText="Subject"
                SortExpression="Subject" UniqueName="Subject">
            </telerik:GridBoundColumn>
            <telerik:GridBoundColumn DataField="Description" HeaderText="Description"
                SortExpression="Description" UniqueName="Description">
            </telerik:GridBoundColumn>
            <telerik:GridBoundColumn DataField="City" HeaderText="City"
                SortExpression="City" UniqueName="City">
            </telerik:GridBoundColumn>
        </Columns>
    </MasterTableView>
        </telerik:RadGrid>
        </div>
        </td>
    </tr>
    </table>
     
    </asp:Content>

    Code Behind
    ---------------------

    using System;
    using System.Collections;
    using System.Collections.Specialized;
    using System.Web.UI;
    using Telerik.Web.UI;
    using Telerik.Web.UI.Scheduler.Views;
    using System.Globalization;
     
    namespace RM
    {
        public partial class Dispatch : System.Web.UI.Page
        {
            protected void Page_Load(object sender, EventArgs e)
            {
     
            }
     
            protected void rsService_AppointmentInsert(object sender, SchedulerCancelEventArgs e)
            {
                e.Appointment.Attributes["Due"] = e.Appointment.Start.AddDays(1).ToString("yyyy/MM/dd HH:mm", CultureInfo.InvariantCulture);
                e.Appointment.Attributes["Priority"] = "Medium";
            }
     
            protected void rgService_RowDrop(object sender, GridDragDropEventArgs e)
            {
                GridDataItem dataItem = e.DraggedItems[0];
     
                Hashtable values = new Hashtable();
                dataItem.ExtractValues(values);
     
     
                //kjhkljhklhkhklhlhklh
                int id = (int)dataItem.GetDataKeyValue("AppointmentID");
                string subject = (string)values["Subject"];
                string targetSlotIndex = TargetSlotHiddenField.Value;
     
                if (targetSlotIndex != string.Empty)
                {
                    HandleSchedulerDrop(id, subject, targetSlotIndex);
                    TargetSlotHiddenField.Value = string.Empty;
                }
                rsService.Rebind();
                rgService.Rebind();
                RadAjaxManager1.AjaxSettings.AddAjaxSetting(rgService, rsService);
            }
     
            private void HandleSchedulerDrop(int id, string subject, string targetSlotIndex)
            {
                rsService.Rebind();
     
                ISchedulerTimeSlot slot = rsService.GetTimeSlotFromIndex(targetSlotIndex);
     
                TimeSpan duration = TimeSpan.FromHours(1);
                if (slot.Duration == TimeSpan.FromDays(1))
                {
                    duration = slot.Duration;
                }
     
                ScheduleAppointment(id, subject, slot.Start, slot.Start.Add(duration));
            }
     
     
            protected void rsService_AppointmentCommand(object sender, AppointmentCommandEventArgs e)
            {
                if (e.CommandName == "Unschedule")
                {
                    int id = (int)e.Container.Appointment.ID;
     
                    DateTime dueDate = DateTime.Now;
     
                    if (!string.IsNullOrEmpty(e.Container.Appointment.Attributes["Due"]))
                        dueDate = Convert.ToDateTime(e.Container.Appointment.Attributes["Due"]);
     
                    string priority = "Medium";
     
                    if (!string.IsNullOrEmpty(e.Container.Appointment.Attributes["Priority"]))
                        priority = e.Container.Appointment.Attributes["Priority"];
     
                    UnscheduleAppointment(id, dueDate, priority);
                    rsService.Rebind();
                    rgService.Rebind();
     
                    RadAjaxManager1.AjaxSettings.AddAjaxSetting(rsService, rgService);
                }
            }
     
            private void UnscheduleAppointment(int id, DateTime dueDate, string priority)
            {
                IDataSource dataSource = GridDS;
                DataSourceView view = dataSource.GetView("DefaultView");
     
                IOrderedDictionary data = new OrderedDictionary();
                data.Add("Start", null);
                data.Add("End", null);
                data.Add("Due", dueDate);
                data.Add("Priority", priority);
     
                IDictionary keys = new OrderedDictionary();
                keys.Add("AppointmentID", id);
     
                view.Update(keys, data, new OrderedDictionary(), OnDataSourceOperationComplete);
            }
     
            private void ScheduleAppointment(int id, string subject, DateTime start, DateTime end)
            {
                IDataSource dataSource = SchedulerDS;
                DataSourceView view = dataSource.GetView("DefaultView");
     
                IOrderedDictionary data = new OrderedDictionary();
                data.Add("Subject", subject);
                data.Add("Start", start);
                data.Add("End", end);
     
                IDictionary keys = new OrderedDictionary();
                keys.Add("AppointmentID", id);
     
                view.Update(keys, data, new OrderedDictionary(), OnDataSourceOperationComplete);
            }
     
            private static bool OnDataSourceOperationComplete(int count, Exception e)
            {
                if (e != null)
                {
                    throw e;
                }
                return true;
            }
     
            protected void rgService_ItemCreated(object sender, GridItemEventArgs e)
            {
                if (e.Item is GridFooterItem && rgService.MasterTableView.IsItemInserted)
                {
                    e.Item.Visible = false;
                }
            }
     
            protected void rgService_ItemCommand(object source, GridCommandEventArgs e)
            {
                if (e.CommandName == RadGrid.InitInsertCommandName)
                {
                    e.Canceled = true;
                    //Prepare an IDictionary with the predefined values
                    ListDictionary newValues = new ListDictionary();
                    newValues["Priority"] = "High";
                    newValues["Due"] = DateTime.Now;
                    newValues["Subject"] = "New task";
                    //Insert the item and rebind
                    e.Item.OwnerTableView.InsertItem(newValues);
                }
            }
        }
    }
  3. Peter
    Admin
    Peter avatar
    6637 posts

    Posted 20 Jul 2011 Link to this post

    Hi Clark,

    Attached is a simple demo for reference. I hope you find it helpful.

    Best wishes,
    Peter
    the Telerik team

    Register for the Q2 2011 What's New Webinar Week. Mark your calendar for the week starting July 18th and book your seat for a walk through of all the exciting stuff we will ship with the new release!

  4. Shawn Clabough
    Shawn Clabough avatar
    17 posts
    Member since:
    Jun 2004

    Posted 27 Aug 2011 Link to this post

    FYI, If anyone is using this with the Entity Framework and an EntityDataSource and cannot get the unschedule to work, this is what I had to do.  I traced it down to the start and end not being updated to null even though I had those properties nullable = true.  This code is actually simpler too.  Note: I was not using due and priority in my test.  I'm also using entity stubbing to save a db round-trip.

    private void UnscheduleAppointment(int id)
    {
        var dc = new ScheduleTestEntities();
     
        var appointment = new Appointment() {AppointmentID = id};
        dc.Appointments.Attach(appointment);
     
        appointment.StartTime = null;
        appointment.EndTime = null;
     
        dc.SaveChanges();
    }
     
     
    private void ScheduleAppointment(int id, string subject, DateTime start, DateTime end)
    {
        var dc = new ScheduleTestEntities();
        var appointment = new Appointment() { AppointmentID = id };
        dc.Appointments.Attach(appointment);
     
        appointment.Subject = subject;
        appointment.StartTime = start;
        appointment.EndTime = end;
     
        dc.SaveChanges();
    }
  5. Plamen
    Admin
    Plamen avatar
    3079 posts

    Posted 31 Aug 2011 Link to this post

    Hello Shawn,

    Thank you for sharing this knowledge with the community.

    Greetings,
    Plamen Zdravkov
    the Telerik team

    Thank you for being the most amazing .NET community! Your unfailing support is what helps us charge forward! We'd appreciate your vote for Telerik in this year's DevProConnections Awards. We are competing in mind-blowing 20 categories and every vote counts! VOTE for Telerik NOW >>

Back to Top