RadAsyncUpload event when clicking Select

1 Answer 30 Views
AsyncUpload Grid
Margo Noreen
Top achievements
Rank 1
Veteran
Margo Noreen asked on 12 Mar 2024, 06:04 PM | edited on 12 Mar 2024, 06:12 PM

We have a RadAsyncUpload control on a page.  The "Select" button is displayed to allow the user to choose files.  All good.  What we'd like is a way to detect when the Select button is clicked to clean up other parts of the page. 

For example... we also have a RadGrid on the page.  The user might have a row open in an EditForm.  We'd like to close that edit form when the user clicks the Select button of the RadAsyncUpload control.  I don't see an obvious client side event for that, and the Select button doesn't trigger a server side event.  

Is there a client-side equivalent for the RadGrid ClearEditItems method that could be called as part of the click event on the RadAsyncUpload Select button?

Any suggestions would be appreciated.

1 Answer, 1 is accepted

Sort by
0
Rumen
Telerik team
answered on 13 Mar 2024, 09:40 AM

Hi Margo,

You can achieve this by adding a client-side event to the "Select" button of the RadAsyncUpload control. You can use the OnClientFilesSelected event to detect when files have been selected by the user. Here is an example of how to use this event to close the edit form of a RadGrid:

        <script type="text/javascript">
            function pageLoad() {
                // Find the Select button of the RadAsyncUpload control. Adjust the selector as needed.
                var selectButton = document.querySelector('.RadAsyncUpload .ruFileInput');
                if (selectButton) {
                    // Attach a click event listener to the Select button
                    selectButton.addEventListener('click', function () {
                        // Get a reference to the RadGrid
                        var grid = $find("<%= RadGrid1.ClientID %>");
                        // Check if an item is in edit mode and close the edit form
                        if (grid && grid.get_editItems().length > 0) {
                            grid.get_masterTableView().fireCommand("Cancel", "")
                        }
                    });
                }
            }

            function OnClientFilesSelected(sender, args) {
                // Get a reference to the RadGrid
                var grid = $find("<%= RadGrid1.ClientID %>");
                // Check if an item is in edit mode and close the edit form
                if (grid && grid.get_editItems().length > 0) {
                    grid.get_masterTableView().fireCommand("Cancel", "")
                }
            }
        </script>

You can add this event to the RadAsyncUpload control in your ASPX page like this:

<telerik:RadAsyncUpload runat="server" ID="RadAsyncUpload1">
    <ClientEvents OnClientFilesSelected="OnClientFilesSelected" />
</telerik:RadAsyncUpload>

If the OnClientFileSelected is to late and you still need to cancel the grid editing by clicking on the Select button, you can attach a click handler to the Select button like this:

        <script type="text/javascript">
            function pageLoad() {
                // Find the Select button of the RadAsyncUpload control. Adjust the selector as needed.
                var selectButton = document.querySelector('.RadAsyncUpload .ruFileInput');
                if (selectButton) {
                    // Attach a click event listener to the Select button
                    selectButton.addEventListener('click', function () {
                        // Get a reference to the RadGrid
                        var grid = $find("<%= RadGrid1.ClientID %>");
                        // Check if an item is in edit mode and close the edit form
                        if (grid && grid.get_editItems().length > 0) {
                            grid.get_masterTableView().fireCommand("Cancel", "")
                        }
                    });
                }
            }
        </script>

        <telerik:RadAsyncUpload runat="server" ID="RadAsyncUpload1" ></telerik:RadAsyncUpload>

Here are my test files:

ASPX

        <script type="text/javascript">
            function pageLoad() {
                // Find the Select button of the RadAsyncUpload control. Adjust the selector as needed.
                var selectButton = document.querySelector('.RadAsyncUpload .ruFileInput');
                if (selectButton) {
                    // Attach a click event listener to the Select button
                    selectButton.addEventListener('click', function () {
                        // Get a reference to the RadGrid
                        var grid = $find("<%= RadGrid1.ClientID %>");
                        // Check if an item is in edit mode and close the edit form
                        if (grid && grid.get_editItems().length > 0) {
                            grid.get_masterTableView().fireCommand("Cancel", "")
                        }
                    });
                }
            }
        </script>

        <telerik:RadAsyncUpload runat="server" ID="RadAsyncUpload1" ></telerik:RadAsyncUpload>


        <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"
                        FilterControlAltText="Filter ShipCountry column" HeaderText="ShipCountry"
                        SortExpression="ShipCountry" UniqueName="ShipCountry">
                    </telerik:GridBoundColumn>
                </Columns>
            </MasterTableView>
        </telerik:RadGrid>

ASPX.CS

using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Configuration;
using System.Web.Security;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Telerik.Web.UI;
using System.Drawing;
using System.Collections.Generic;
using Telerik.Web.UI.Skins;
using System.IO;
using System.Linq;
using System.Collections;

public partial class Default : System.Web.UI.Page 
{
    #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)
    {
        (sender as Telerik.Web.UI.RadGrid).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


}





I hope this helps! Let me know if you have any further questions.

    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
    Margo Noreen
    Top achievements
    Rank 1
    Veteran
    commented on 13 Mar 2024, 05:13 PM | edited

    Hello Rumen, thank you for your quick response and example code!  Here's a follow-up question/problem (and hard stop for trying out your client side code...).  I use the $find method to get a reference to the grid, and do get back an object.  However, the  get_masterTableView() seems to only return null, so I'm unable to proceed.  I've attached a screengrab of a snippet when stepping through javascript code in the Firefox debugger:

                var grid = $find('<%= gridEFolderList.ClientID %>');
                var masterTable = grid.get_masterTableView();
    
     
    I find it "odd' that $find does get back a valid object, but the subsequent call to get_masterTableView() retuns null.  I've tried a few other js methods, e.g. get_id() or get_visible(), and these do return valid values.

     

    I've attached another screengrab for the console window that shows the "grid" variable that was returned by the $find() method and some of the subsequent method calls on it.  Some return valid values, as mentioned, some return empty arrays.  The call to get_editItems() threw an "Uncaught TypeError:  k is null"

    Rumen
    Telerik team
    commented on 14 Mar 2024, 09:52 AM

    The grid might not be fully initialized when you call get_masterTableView(). This can occur if the script is executed before the grid is completely loaded on the page. 

    While I am unable to reproduce the issue with the following code and check:

            <script type="text/javascript">
                function OnClientFilesSelected(sender, args) {
                    // Get a reference to the RadGrid
                    var grid = $find("<%= gridEFolderList.ClientID %>");
                    
                    // Check if an item is in edit mode and close the edit form
                    if (grid && grid.get_editItems().length > 0) {
                      //  grid.get_masterTableView().fireCommand("Cancel", "");
                        grid.get_masterTableView().cancelAll();
                    }
                }
            </script>

    but, there are forums discussing get_masterTableView is null (undefined) issue: 

    For your convenience, I have also attached a simple runnable project demonstrating the solution which you can use as a base to compere with your project and find the reason for the error.

     

    Margo Noreen
    Top achievements
    Rank 1
    Veteran
    commented on 14 Mar 2024, 01:35 PM | edited

    Rumen - I'm afraid that is not the case. The screenshots I've shown you are from a fully rendered page.  I invoked the sample javascript 2 ways.  First, by clicking the "Select" button on the asyncupload control.  As you've shown in your sample code, I have a OnClientFilesSelected method assigned to that control and it dutifully invoked my test JS function.  I've also tested this, again after the page is fully loaded and sitting "idle" in a browser window, by opening a JS console window (debug tools in Firefox or Edge or Chrome, I've tested in all them), then calling my test JS function. 

    In both cases, the JS function does get reference to the RadGrid, but still returns null from the get_masterTableView() method.  

    When I search on this issue (google or whatever), I get a lot of hits on the page not rendered, but that is not the case here.  What else can we do to troubleshoot and resolve this problem?

    I've also attached additional screengrabs to highlight the issue, and I think it shows what I was describing.  I call my test javascript function and use console.log to show the results.  Note that I do get a "grid" reference, null from the get_masterTableView() method, and a JS error for the get_editItems():

    "Uncaught TypeError: k is null"

    Hopefully this provides some more clues.

    Margo Noreen
    Top achievements
    Rank 1
    Veteran
    commented on 14 Mar 2024, 02:46 PM

    What to know how to break your sample project... and "fix" the issue I've encountered?

    The culprit seems to be:

    ClientIDMode="Static"

    If you set this attribute on the grid, you get the results I was documenting (null master table, uncaught type error, etc.).  If you remove it, it all works.

    Is this something that Telerik can fix?

    Rumen
    Telerik team
    commented on 14 Mar 2024, 03:22 PM

    I am glad that you found the reason for the problem!

    The ClientIDMode="Static" case is discussed in the following KB article: https://docs.telerik.com/devtools/aspnet-ajax/knowledge-base/clientidmode-static-breaks-controls-functionality

    Microsoft recommends using ClientIDMode="Static" only for static controls. The Telerik controls, on the other hand, are controls with complex hierarchies of child controls and templates so setting their ClientID mode to static will break their functionality.

    To solve this issue, use the AutoID mode for the Telerik controls on the page especially when they are performing AJAX requests.

     

    Margo Noreen
    Top achievements
    Rank 1
    Veteran
    commented on 14 Mar 2024, 07:25 PM | edited

    Setting aside the ClientIDMode issue... 

    Using the radgridtest project you provided:

    - I click the edit icon in the grid to put that row into edit mode

    - then I click the Select button on the asyncupload control and choose a file

    - the JS code does fire and closes up the grid, but... it also clears the selection from asyncupload control.  No file is show as selected.

    It almost feels like it's causing a postback.  So I added a textbox to the page, and on the codebehind page, simply added some code to the PageLoad method to set the text of that textbox to a timestamp.  Then I repeat the steps above. And sure enough, the timestamp does get updated after clicking the Select.

     

    Rumen
    Telerik team
    commented on 18 Mar 2024, 03:35 PM

    Here is the solution you are looking for, e.g. we perform an ajax request when the upload is clicked and the grid is in edit mode which triggers the following ajax request handler and cancels the grid editing and fires a JS function to re-click the Select button: 

        protected void RadAjaxManager1_AjaxRequest(object sender, AjaxRequestEventArgs e)
        {
            if (e.Argument == "CanelEditSelectFile")
            {
                gridEFolderList.Items[0].FireCommandEvent("CancelAll", "");
    
                string selecFileScript = "function f(){ selectFile(); Sys.Application.remove_load(f);}; Sys.Application.add_load(f);";
                ScriptManager.RegisterStartupScript(Page, Page.GetType(), "MyScript", selecFileScript, true);
            }
        }

            <telerik:RadScriptBlock ID="RadScriptBlock1" runat="server">
                <script type="text/javascript">
                    var grid, ajaxManager;
    
                    function pageLoadHandler() {
                        grid = $find("<%= gridEFolderList.ClientID %>");
                        ajaxManager = $find("<%= RadAjaxManager1.ClientID %>");
    
                        $telerik.$(".RadAsyncUpload .ruFileInput").on("click", function (e) {
                            if (grid.get_editItems().length > 0) {
                                e.preventDefault();
                                e.stopPropagation();
    
                                ajaxManager.ajaxRequest("CanelEditSelectFile");
                            }
                        });
                    }
                    Sys.Application.add_load(pageLoadHandler);
    
                    function selectFile() {
                        $telerik.$(".RadAsyncUpload .ruFileInput").click();
                    }
                </script>
            </telerik:RadScriptBlock>

    Here is the whole solution:

    ASPX

            <telerik:RadScriptManager ID="RadScriptManager1" runat="server">
                <Scripts>
                    <asp:ScriptReference Assembly="Telerik.Web.UI" Name="Telerik.Web.UI.Common.Core.js" />
                    <asp:ScriptReference Assembly="Telerik.Web.UI" Name="Telerik.Web.UI.Common.jQuery.js" />
                    <asp:ScriptReference Assembly="Telerik.Web.UI" Name="Telerik.Web.UI.Common.jQueryInclude.js" />
                </Scripts>
            </telerik:RadScriptManager>
    
    
            <telerik:RadAsyncUpload ID="RadAsyncUpload1" runat="server"></telerik:RadAsyncUpload>
    
            <telerik:RadScriptBlock ID="RadScriptBlock1" runat="server">
                <script type="text/javascript">
                    var grid, ajaxManager;
    
                    function pageLoadHandler() {
                        grid = $find("<%= gridEFolderList.ClientID %>");
                        ajaxManager = $find("<%= RadAjaxManager1.ClientID %>");
    
                        $telerik.$(".RadAsyncUpload .ruFileInput").on("click", function (e) {
                            if (grid.get_editItems().length > 0) {
                                e.preventDefault();
                                e.stopPropagation();
    
                                ajaxManager.ajaxRequest("CanelEditSelectFile");
                            }
                        });
                    }
                    Sys.Application.add_load(pageLoadHandler);
    
                    function selectFile() {
                        $telerik.$(".RadAsyncUpload .ruFileInput").click();
                    }
                </script>
            </telerik:RadScriptBlock>
    
            <telerik:RadAjaxManager ID="RadAjaxManager1" runat="server" OnAjaxRequest="RadAjaxManager1_AjaxRequest">
                <AjaxSettings>
                    <telerik:AjaxSetting AjaxControlID="gridEFolderList">
                        <UpdatedControls>
                            <telerik:AjaxUpdatedControl ControlID="gridEFolderList" />
                        </UpdatedControls>
                    </telerik:AjaxSetting>
                </AjaxSettings>
                <AjaxSettings>
                    <telerik:AjaxSetting AjaxControlID="RadAjaxManager1">
                        <UpdatedControls>
                            <telerik:AjaxUpdatedControl ControlID="gridEFolderList" />
                        </UpdatedControls>
                    </telerik:AjaxSetting>
                </AjaxSettings>
            </telerik:RadAjaxManager>
    
    
            <asp:Label ID="Label1" runat="server" Text="Action:"></asp:Label>
    
            <telerik:RadGrid ID="gridEFolderList" 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"
                            FilterControlAltText="Filter ShipCountry column" HeaderText="ShipCountry"
                            SortExpression="ShipCountry" UniqueName="ShipCountry">
                        </telerik:GridBoundColumn>
                    </Columns>
                </MasterTableView>
            </telerik:RadGrid>

    ASPX.CS

       protected void RadAjaxManager1_AjaxRequest(object sender, AjaxRequestEventArgs e)
       {
           if (e.Argument == "CanelEditSelectFile")
           {
               gridEFolderList.Items[0].FireCommandEvent("CancelAll", "");
    
               string selecFileScript = "function f(){ selectFile(); Sys.Application.remove_load(f);}; Sys.Application.add_load(f);";
               ScriptManager.RegisterStartupScript(Page, Page.GetType(), "MyScript", selecFileScript, true);
           }
       }
    
       #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)
       {
           (sender as Telerik.Web.UI.RadGrid).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

    Tags
    AsyncUpload Grid
    Asked by
    Margo Noreen
    Top achievements
    Rank 1
    Veteran
    Answers by
    Rumen
    Telerik team
    Share this question
    or