button to select & copy

Hi experts,

I'm after a button that will copy an item from an asp:repeater to clipboard, the process must be infinitely repeatable so that the user can return and copy something else as many times as they wish.
I don't want the user to have to manually select the text on screen I want the button to do the selecting and copying in one hit.

Is this possible, i'm thinking there could be an indexing issue here given that the text I want is dynamic...



forstersAsked:
Who is Participating?
 
forstersAuthor Commented:
For anyone else trying to do this, my final working code is as follows:
<!------------------------------aspx page---------------------------------------->

 <asp:GridView ID="GridView1" DataSourceID="Passwords" Width="740px" BorderStyle="None" AutoGenerateColumns="false" GridLines="Horizontal" onrowdatabound="GridView1_RowDataBound" EmptyDataText="There are currently no passwords saved under your name" runat="server">
    <Columns>
    <asp:HyperLinkField  DataTextField="SiteName" DataNavigateUrlFields="SiteURL" Target="_blank" ItemStyle-Width="150px" HeaderStyle-HorizontalAlign="Left" SortExpression="SiteName"/>
     <asp:TemplateField HeaderText="Username" ItemStyle-Width="100px" HeaderStyle-HorizontalAlign="Left">
                        <ItemTemplate>
                            <asp:Label ID="Label1" runat="server" Text='<%# Eval("UserName") %>'></asp:Label>
                        </ItemTemplate>
                    </asp:TemplateField>

   
    <asp:TemplateField ItemStyle-HorizontalAlign="Left" ItemStyle-Width="80px">
                        <ItemTemplate>
                            <asp:Button ID="Button1" runat="server" Text="Copy" />
                        </ItemTemplate>
                    </asp:TemplateField>

    <asp:TemplateField HeaderText="Password" ItemStyle-Width="100px" HeaderStyle-HorizontalAlign="Left">
                        <ItemTemplate>
                            <asp:Label ID="Label2" runat="server" Text='<%# Eval("Password") %>'></asp:Label>
                        </ItemTemplate>
                    </asp:TemplateField>

   
    <asp:TemplateField ItemStyle-HorizontalAlign="Left" ItemStyle-Width="80px">
                        <ItemTemplate>
                            <asp:Button ID="Button2" runat="server" Text="Copy" />
                        </ItemTemplate>
                    </asp:TemplateField>
   
    </Columns>

    </asp:GridView>

<!--------------------------JavaScript-------------------------------------------->

 <script type="text/javascript">
            function CopyGridView(target) {
                var div = document.getElementById(target);
                div.contentEditable = 'true';
                var controlRange;
                if (document.body.createControlRange) {
                    controlRange = document.body.createControlRange();
                    controlRange.addElement(div);
                    controlRange.execCommand('Copy');
                }
                div.contentEditable = 'false';
                return false;
            }
    </script>

<!------------------C# code behind--------------------------------------------->
  protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            Label lbl1 = e.Row.FindControl("Label1") as Label;
            Button btn1 = e.Row.FindControl("Button1") as Button;
            btn1.Attributes.Add("onclick", "return CopyGridView('" + lbl1.ClientID + "')");
       
            Label lbl2 = e.Row.FindControl("Label2") as Label;
            Button btn2 = e.Row.FindControl("Button2") as Button;
            btn2.Attributes.Add("onclick", "return CopyGridView('" + lbl2.ClientID + "')");
        }
    }
0
 
Easwaran ParamasivamCommented:
Below code is used to copy the given content into Clipboard. Convert the repeater content into HTML using rendercontrol method and pass the content to the javascript function.
function copyToClipboard(s)
{
	if( window.clipboardData && clipboardData.setData )
	{
		clipboardData.setData("Text", s);
	}
	else
	{
		user_pref("signed.applets.codebase_principal_support", true);
		netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');

		var clip Components.classes['@mozilla.org/widget/clipboard;[[[[1]]]]'].createInstance(Components.interfaces.nsIClipboard);
		if (!clip) return;

		// create a transferable
		var trans = Components.classes['@mozilla.org/widget/transferable;[[[[1]]]]'].createInstance(Components.interfaces.nsITransferable);
		if (!trans) return;

		// specify the data we wish to handle. Plaintext in this case.
		trans.addDataFlavor('text/unicode');

		// To get the data from the transferable we need two new objects
		var str = new Object();
		var len = new Object();

		var str = Components.classes["@mozilla.org/supports-string;[[[[1]]]]"].createInstance(Components.interfaces.nsISupportsString);

		var copytext=meintext;

		str.data=copytext;

		trans.setTransferData("text/unicode",str,copytext.length*[[[[2]]]]);

		var clipid=Components.interfaces.nsIClipboard;

		if (!clip) return false;

		clip.setData(trans,null,clipid.kGlobalClipboard);	   
	}
}

Open in new window

0
Ultimate Tool Kit for Technology Solution Provider

Broken down into practical pointers and step-by-step instructions, the IT Service Excellence Tool Kit delivers expert advice for technology solution providers. Get your free copy now.

 
forstersAuthor Commented:
Hi, thanks I should perhaps revise the question; I can get the javascript to select and copy but I think because the items are in a repeat region it defaults to selecting the first item in the list:

So for example if I have a list of numbers 1 - 10 that I'm displaying from a datatable in my repeat region, when I add the button code I have ten buttons one for each number (because they too are in the repeat region) but my buttons don't know which number in the list they refer to.. so whatever button I click it just takes the first item (number 1) is there a way round this? So that the buttons know that the data is dynamic, normally this would involve referring to the items by their index - so 1 would have an index of 0  but i'm not sure how i'd work that into the javascript. The rest of the page is asp.net using VB.
0
 
forstersAuthor Commented:
EaswaranP thanks for your post, can you show me what you mean by the rendercontrol method, I'm not familiar...

I attach the repeater code as it stands and have amended my script to the code you posted
<ASP:Repeater runat="server" DataSource='<%# Data.DefaultView %>' >
            
              <ItemTemplate>
  
              <tr>
                            <td><pre id="pre"><%# Data.FieldValue("Title", Container) %></pre></td>
              <td><button id="copy" onclick="copyToClipboard(document.getElementById('pre').innerHTML)">Copy</button>
</td>
                            </tr>
             
              </ItemTemplate>
            </ASP:Repeater>

Open in new window

0
 
Kiran SonawaneProject LeadCommented:
Use jquery
$(document).ready(function(){
  $('#copy').click(function(){
   var htm =  $(this).closest('tr').find("pre").html();
    copyToClipboard(htm);
  });
});

Open in new window

0
 
Kiran SonawaneProject LeadCommented:
And remove onclick even i.e. onclick="copyToClipboard(document.getElementById('pre').innerHTML)". So your button html will be

<button id="copy">Copy</button>
0
 
forstersAuthor Commented:
Hi Sonawanekiran

Many thanks, I can't get that to work for me I'm afraid, it doesn't appear to copy anything as when I come to paste I'm just pasting the last item that was copied to my clipboard.

Had I got it to work my next question would have been what If I have more than one item in my <tr> - which I do, I just stripped it down to one for simplicity...
0
 
forstersAuthor Commented:
The solution that ultimately worked for me was without doubt thanks to the experts help, but for anyone else trying to follow this, the actual working solution is in my post hence why I have indicated that as being the solution. Hope someone finds it helpful.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.