Archive

Posts Tagged ‘paste feature’

Disable copy paste on textbox in the ASP.Net/C# using javascript/Jquery

March 15, 2012 2 comments

Very simple method to disable copy paste in the textbox without any extra script

To achieve some requirements like disable copy paste functionalities in the textbox in aspx page, commonly we need to write some additional javascript functionalities in the aspx page. We can achieve this features using very simple methods.

First Method to disable Ctrl Key and right click on textbox

This method is very simple method and here we don’t need to include any javascript methods or files. We are having oncopy and onpaste event for the textboxes and can call return false for this both event.

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="disableCopyPaste.aspx.cs"
 Inherits="ExperimentLab.disableCopyPaste" %>
<!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 id="Head1" runat="server">
 <title>Sample to Disable Copy, Cut and Paste Options in textbox</title>
</head>
<body>
 <form id="form2" runat="server">
 <div>
 <strong>First Method To disable copy, cut and paste options in textbox</strong><br />
 <asp:TextBox ID="TextBox2" runat="server" oncopy="return false" oncut="return false"
 onpaste="return false"></asp:TextBox>
 </div>
 </form>
</body>
</html>

Second method to prevent copy paste feature in the aspx texbox

In this option, we are calling a javascript function on any key press. This function checks whether user press ctrl key or right click using e.keyCode and e.button variable. If the user press ctrl key or right click, from the javascript function call return false

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="disableCopyPaste.aspx.cs"
 Inherits="ExperimentLab.disableCopyPaste" %>
<!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 id="Head1" runat="server">
 <title>Sample to Disable Copy, Cut and Paste Options in textbox</title>
 <script language="javascript" type="text/javascript">
//Function to disable Cntrl key/right click
function DisableControlKey(e) {
// Message to display
var message = "Cntrl key/ Right Click Option disabled";
// Condition to check mouse right click / Ctrl key press
if (e.keyCode == 17 || e.button == 2) {
alert(message);
return false;
}
}
</script>
</head>
<body>
 <form id="form2" runat="server">
 <div>
 <strong>Second Method to Disable copy, cut and paste options in textbox</strong><br />
 <asp:TextBox ID="TextBox3" runat="server" onKeyDown="return DisableControlKey(event)"
 onMouseDown="return DisableControlKey(event)"></asp:TextBox>
 </div>
 </form>
</body>
</html>