Your Privacy Matters: We use our own and third-party cookies to improve your experience on our website. By continuing to use the website we understand that you accept their use. Cookie Policy
280
Copy and Paste Excel data at the end of the grid
posted

I'm trying to add functionality to the webDataGrid so the user can copy multiple rows from Excel and then paste them in at the end of the existing grid.  I've cannibalized the copy paste code from a different thread, and got that to work as far as pasting over existing data, but I can't get it to just paste in at the end of the grid. 

Here's the template code:

<ig:WebDataGrid

ID="WebDataGrid1"

runat="server"

Height="350px"

Width="400px"

AutoGenerateColumns="False"

DataKeyFields="ID"

ClientIDMode="Static"

>

<ClientEvents KeyUp="keyUp" />

<Behaviors>

<ig:Selection CellClickAction="Cell" CellSelectType="Single">

</ig:Selection>

<ig:Activation>

</ig:Activation>

<ig:EditingCore>

<Behaviors>

<ig:CellEditing></ig:CellEditing>

</Behaviors>

</ig:EditingCore>

</Behaviors>

<Columns>

<ig:BoundDataField Key="ID" DataFieldName="ID" Hidden="true" />

<ig:BoundDataField Key="ReqID" DataFieldName="ReqID" Header-Text="ReqID" />

<ig:BoundDataField Key="Description" DataFieldName="Description" Header-Text="Description" />

</Columns>

</ig:WebDataGrid>

 

And here's the javascript I'm using for the paste operation:

 

function keyUp(grid, args)

{

var evt = args.get_browserEvent();

if (evt.ctrlKey && evt.keyCode == 86) // Ctrl-V

{

var activeCell = grid.get_behaviors().get_activation().get_activeCell();

var clipboardText = getClipboardData();

if (activeCell && clipboardText)

{

//initialize grid variable

var grid = $find("WebDataGrid1");

var rows = grid.get_rows();

// Excel stores its data in text clipboard separated

// by \n between rows and by \t between cells

var pasteData = clipboardText.split("\n");

// Last row may be a dummy row

if (pasteData[pasteData.length - 1].length == 1 && pasteData[pasteData.length - 1][0] == "")

delete pasteData[pasteData.length - 1];

var newID = grid.get_rows().get_length();

for (var i = 0; i < pasteData.length; i++) {

    newID = newID + 1;

    pasteData[i] = pasteData[i].split("\t");

 

var newRow = new Array(newID, "ReqID", "Description");

    rows.add(newRow);

}

var rowDataIndex = 0;

var rowIndex = activeCell.get_row().get_index();

var rowIndex = grid.get_rows().get_length()

// Let's paste until the end of our clipboard data or until the end of the grid rows

while (rowDataIndex < pasteData.length && rowIndex < grid.get_rows().get_length())

{

//     var row = grid.get_rows().get_row(rowIndex++);

var row = grid.get_rows().get_row(newID);

var cellDataIndex = 0;

// var cellData = pasteData[rowDataIndex++];

var cellData = pasteData[newID];

var cellIndex = activeCell.get_index();

//Let's paste until the end of the clipboard data or until the end of the cells

while (cellData && cellDataIndex < cellData.length && cellIndex < row.get_cellCount())

{

var text = cellData[cellDataIndex++];

if (text === null)

break;

var cell = row.get_cell(cellIndex++);

cell.set_value(text);

}

}

}

}

}

Right now all it does is paste the one row at the end.  I feel like I'm close on this, just not that experienced with Infragistics and rusty on Javascript.  Any suggestions would be appreciated.

  • 280
    Verified Answer
    posted

    I figured out a workaround.  Seen a lot of people looking for this, hope it helps

     

    <%@ Page Language="C#" AutoEventWireup="true" CodeFile="copyPaste.aspx.cs" Inherits="copyPaste" %>

    <%@ Register Assembly="Infragistics4.Web.v11.1, Version=11.1.20111.2225, Culture=neutral, PublicKeyToken=7dd5c3163f2cd0cb" Namespace="Infragistics.Web.UI.GridControls" TagPrefix="ig" %>

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <html xmlns="http://www.w3.org/1999/xhtml">

    <head runat="server">

    <title></title>

    <asp:PlaceHolder runat="server">

    <script type="text/javascript">

    function keyUp(grid, args)

    {

    var evt = args.get_browserEvent();

    if (evt.ctrlKey && evt.keyCode == 86) // Ctrl-V

    {

    var activeCell = grid.get_behaviors().get_activation().get_activeCell();

    var clipboardText = getClipboardData();


    if (activeCell && clipboardText)

    {

     //initialize rows variable

    var rows = grid.get_rows();

     

    // Excel stores its data in text clipboard separated

    // by \n between rows and by \t between cells

     

    var pasteData = clipboardText.split("\n");

    //paste clipboard data into

    var txtData = document.getElementById("<%= txtPasteData.ClientID %>")

    txtData.value = pasteData;

     

    var check = "<%= Button1.ClientID %>";

    return __doPostBack("<%= Button1.ClientID %>", '');

    return false;

    }

    }

    }

     

    var _browserPasteData = null;

    function getClipboardData()

    {

    if (_browserPasteData) // Safari/Chrome logic

    return _browserPasteData;


     

    if (window.clipboardData) // IE logic

    {

    return window.clipboardData.getData("Text");

    }

    else if (typeof(netscape) != "undefined") // Firefox logic

    {

    netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');

     

    var clip = Components.classes["@mozilla.org/widget/clipboard;1"].createInstance(Components.interfaces.nsIClipboard);

     

    var trans = Components.classes["@mozilla.org/widget/transferable;1"].createInstance(Components.interfaces.nsITransferable);

    trans.addDataFlavor("text/unicode");

    clip.getData(trans, clip.kGlobalClipboard);

    var str = new Object();

    var len = new Object();

    trans.getTransferData("text/unicode", str, len);

     

    if (str)

    return str.value.QueryInterface(Components.interfaces.nsISupportsString).toString();

    }

     

    return null;

    }

    // In Safari/Chrome the clipboard data can only be accessed

    // from the onpaste event. In this sample the event is handled

    // off the body element: <body onpaste="browserPaste(event)">

     

    function browserPaste(e)

    {

    _browserPasteData = e.clipboardData && e.clipboardData.getData ?

    e.clipboardData.getData('text/plain') : null;

    }

    </script>

    </asp:PlaceHolder>

    </head>

    <body onpaste="browserPaste(event)">

    <form id="form1" runat="server">

    <asp:ScriptManager ID="ScriptManager1" EnablePageMethods="true" runat="server"></asp:ScriptManager>

    <div>

    <ig:WebDataGrid

    ID="WebDataGrid1" EnableAjax="true"

    runat="server"

    Height="700px"

    Width="600px"

    AutoGenerateColumns="False"

    DataKeyFields="ID"

    ClientIDMode="Static">

    <ClientEvents KeyUp="keyUp" />

    <Behaviors>

    <ig:Selection CellClickAction="Cell" CellSelectType="Single">

    </ig:Selection>

    <ig:Activation>

    </ig:Activation>

    <ig:EditingCore>

    <Behaviors>

    <ig:CellEditing>

    </ig:CellEditing>

    </Behaviors>

    </ig:EditingCore>

    </Behaviors>

    <Columns>

    <ig:BoundDataField Key="ID" DataFieldName="ID" Hidden="true" />

    <ig:BoundDataField Key="ReqID" DataFieldName="ReqID" Header-Text="ReqID" />

    <ig:BoundDataField Key="Description" DataFieldName="Description" Header-Text="Description" />

    </Columns>

    </ig:WebDataGrid>

    <asp:TextBox ID="txtPasteData" onblur="__doPostBack('Button1','')" AutoPostBack="true" Height="0" Width="0" runat="server" />

    <input id="Button1" type="button" value="button" style="display:none" runat="server" />

    <input type="hidden" name ="__EVENTTARGET" value ="">

    <input type="hidden" name ="__EVENTARGUMENT" value ="">

    </div>

    </form>

    </body>

    </html>

     

    using System;

    using System.Collections.Generic;

    using System.Linq;

    using System.Web;

    using System.Web.UI;

    using System.Web.UI.WebControls;

    using System.Data;


    public partial class copyPaste : System.Web.UI.Page

    {

     

    protected void Page_Load(object sender, EventArgs e)

        {

     

    if (!Page.IsPostBack)

            {

    this.WebDataGrid1.DataSource = this.GetDataSource();

    this.WebDataGrid1.DataBind();

            }

    else if(this.txtPasteData.Text.Length > 0)

            {

    string pasteData = txtPasteData.Text;

                splitData(pasteData);

                txtPasteData.Text ="";

            }

        }

     

    protected void splitData(string pastedData)

        {

    // Excel stores its data in text clipboard separated

    // by \n between rows and by \t between cells

    //var pasteData = clipboardText.split("\n");

    string[] separator = new string[] { "," };

    string[] strSplitArr = pastedData.Split( separator, StringSplitOptions.RemoveEmptyEntries); 

            AddToDataSource(strSplitArr);

        }

    DataTable GetDataSource()

    {

    if (this.Session["DataSource"] != null)

    return this.Session["DataSource"] as DataTable;

    DataTable table = new DataTable();

            table.Columns.Add("ID", typeof(int));

    table.Columns.Add("ReqID", typeof(string));

            table.Columns.Add("Description", typeof(string));

    //table.PrimaryKey = new DataColumn[] { table.Columns[0] };

            table.Rows.Add(new object[] { 0, "1.1.1", "Site must follow BOA CSS standards" });

            table.Rows.Add(new object[] { 1, "1.1.2", "Need admin tables to change drop down values" });

            table.Rows.Add(new object[] { 2, "1.1.3", "Must have error handling" });

            table.Rows.Add(new object[] { 3, "1.1.4", "Log files need to be accessible" });

    this.Session["DataSource"] = table;

    return table;

    }

    protected void AddToDataSource(string[] newValues)

        {

    DataTable dt;

    //pull datatable out of session variable if it exists

    if (this.Session["DataSource"] != null)

            {

                dt = (DataTable)Session["DataSource"];

            }

    else

            {

                dt=new DataTable();

            }

    //This is the select query for Max

    string selectCommand = "Max(ID)";

    //returns the Max EmploeeID

    int MaxID = Convert.ToInt32((object)dt.Compute(selectCommand, string.Empty));

    int ID = MaxID + 1;

    //split ReqID and description, add ID field for Infragistics

    foreach (string arrStr in newValues)

            {

    string[] split = arrStr.Split(new Char[] { '\t' });

    if (split.Length > 0)

                {

    string ReqID = split[0];

    string Description = split[1];

                    dt.Rows.Add(

    new object[] {ID, ReqID, Description });

                    ID = ID + 1;

                }

            }

    this.WebDataGrid1.DataSource = dt;

    this.WebDataGrid1.DataBind();

        }

    }