How to Select TextBox text in GridView and Copy to Clipboard with Javascript
Find the text of a TextBox control in an ASP.NET GridView and Copy to Clipboard with Javascript
by
Doug
Updated September 19, 2018
Here's how you can find the text of a particular TextBox witnin an ASP.NET GridView row and then Select and Copy the text to Clipboard with Javascript.
First put the following javascript in the HTML of your page (either in HEAD of your html page or somewhere above the GridView control):
<script type="text/javascript">
//<![CDATA[
function SelectTextandCopyToClipboard(currentTextBox) {
var txtNameUrl;
//Find the GridView Row using the TextBox reference.
var row = currentTextBox.parentNode.parentNode;
//Fetch all controls in GridView Row.
var controls = row.getElementsByTagName("*");
//Loop through the fetched controls.
for (var i = 0; i < controls.length; i++) {
//Find the TextBox control.
if (controls[i].id.indexOf("RecommendUrlTextBox") != -1) {
txtNameUrl = controls[i];
}
}
// Select text
txtNameUrl.select();
// Copy to clipboard
document.execCommand('copy');
}
//]]>
</script>
Here's a sample GridView that corresponds to the Javascript above to Copy inner text from a single TextBox within the GridView
<asp:GridView ID="LinksGridView" runat="server" OnRowDataBound="LinksGridView_RowDataBound"
DataKeyNames="LinkId" DataSourceID="LinksDataSource" PageSize="50">
<Columns>
<asp:BoundField DataField="LinkId" HeaderText="Id" InsertVisible="False"
ReadOnly="True" SortExpression="LinkId" />
<asp:TemplateField HeaderText="Link URL" HeaderStyle-HorizontalAlign="center">
<ItemTemplate>
<asp:TextBox ID="RecommendUrlTextBox" runat="server" Text="These words are will be selected." onclick="SelectTextandCopyToClipboard(this);" Width="200px" BackColor="#FDFEFF" ToolTip="Click to Copy URL"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
</Columns>
Hope that helps...
For other similiar examples check out:
Find and validate TextBox and DropDownList controls in GridView row using JavaScript in ASP.Net
Get ASP.Net GridView Row and its RowIndex when clicked using JavaScript
You may also be interested in the book: JavaScript for .NET Developers