Printing in DotNet is a fundamental aspect of creating client

I have a Gridview and a Title that I want to print on a page. However, there is one cell in the template field that I do not want to include when printing. How can I exclude just that cell? Here is the code snippet:

<div id="Printmeonly" align="center">
<table width="100%">
    <tr id="trtitle" style="display:none">
        <td style="color:Blue;font-size:large" align="center" colspan="2"><strong>Incident # <%=Request.QueryString["Inc"].ToString() %> Notes (Store <%=Request.QueryString["Loc"].ToString() %>)</strong><br /><br /></td>
    </tr>
    <tr>
        <td colspan="2" align="center">
            <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" 
                BackColor="White" BorderColor="#999999" BorderStyle="None" BorderWidth="1px" 
                CellPadding="3"
                DataSourceID="SqlDataSource" ShowFooter="True">
                <RowStyle BackColor="#EEEEEE" ForeColor="Black" />
                <Columns>
                     <asp:BoundField DataField="Somefield" HeaderText="Somefield" 
                         SortExpression="Somefield" Visible="False" />
                     <asp:TemplateField ShowHeader="True" HeaderText="Action" ItemStyle-CssClass="dontPrint"  ControlStyle-CssClass="dontPrint" HeaderStyle-CssClass="dontPrint" FooterStyle-CssClass="dontPrint">
                     <ItemTemplate>
                         <asp:ImageButton ID="bttneditNote" ImageUrl="~/images/bttnEdit.gif" style="cursor:pointer" runat="server" CausesValidation="False" 
                             CommandName="Edit" Text="Edit"></asp:ImageButton>
                        <asp:ImageButton ID="bttndeleteNote" ImageUrl="~/images/bttnDelete.gif" OnClientClick="if(confirm('Are you sure you want to delete this Application?')==false) return false;" style="cursor:pointer" runat="server" CausesValidation="False" 
                             CommandName="Delete" Text="Delete"></asp:ImageButton>
                     </ItemTemplate>
                     <EditItemTemplate>
                          <asp:ImageButton ID="bttnEditNote" ImageUrl="~/images/bttnSave.gif" style="cursor:pointer" runat="server" CausesValidation="False" 
                             CommandName="Update" Text="Update"></asp:ImageButton>
                         &nbsp; <asp:ImageButton ID="bttnCancelNote" ImageUrl="~/images/bttnCancel.gif" style="cursor:pointer" runat="server" CausesValidation="False" 
                             CommandName="Cancel" Text="Cancel"></asp:ImageButton>
                     </EditItemTemplate>
                 </asp:TemplateField>
                </Columns>
                <FooterStyle BackColor="#CCCCCC" ForeColor="Black" />
                <PagerStyle BackColor="#999999" ForeColor="Black" HorizontalAlign="Center" />
                <SelectedRowStyle BackColor="#008A8C" Font-Bold="True" ForeColor="White" />
                <HeaderStyle BackColor="#000084" Font-Bold="True" ForeColor="White" />
                <AlternatingRowStyle BackColor="#DCDCDC" />
            </asp:GridView>
         </td>
    </tr>
 </table>
 </div>
  <table>
<tr>
    <td align="center" colspan="2"><br />
        <asp:ImageButton ID="bttnprint" runat="server" OnClientClick="CallPrint('Printmeonly');" ImageUrl="~/somefolder/images/PrintButton.gif" style="cursor:pointer" />
    </td>
</tr>

<script type="text/javascript'>

function CallPrint(strid) {
    var trtitle = document.getElementById('trtitle');
    trtitle.style.display = '';
    var prtContent = document.getElementById(strid);
    var WinPrint = window.open('', '', 'left=0,top=0,width=1,height=1,toolbar=1,scrollbars=1,status=1');
    WinPrint.document.write(prtContent.innerHTML);
    WinPrint.document.close();
    WinPrint.focus();
    WinPrint.print();
    WinPrint.close();
}
</script>

When I print, I use a Javascript function to specify which div tag id to print. Any ideas on how to remove the specific field from printing?

Edit: I made changes to the markup. The template field with buttons is the one I need to hide.

Answer №1

Have you considered using a CSS method like this:

<style type="text/css">
    @media print {
      .dontPrint { display: none; }
    }
  </style>

You can then assign this class to the element you want to hide when printing. If you need more guidance or options, you can refer to this resource.

Edit:

I took some time to create a complete example which I tested by printing to an XPS document for eco-friendliness. Here's the ASPX code:

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <style type="text/css">   
         @media print       
         {
            .dontPrint { display: none; }    
         }  
    </style>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <asp:GridView ID="grdHideOnPrint" runat="server">
        <Columns>
            <asp:BoundField DataField="Test" />
            <asp:TemplateField ControlStyle-CssClass="dontPrint">
                <ItemTemplate>
                    <asp:Button Text="Hide On Print"  runat="server" ID="btnHideOnPrint" />
                </ItemTemplate>
            </asp:TemplateField>
        </Columns>
    </asp:GridView>
    </div>
    </form>
</body>
</html>

The backend code:

public partial class _Default : System.Web.UI.Page 
{
    public class Testing
    {
        public string Test { get; set;}
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        List<Testing> data = new List<Testing>() 
        {
            new Testing() { Test = "This should print" }
        };

        grdHideOnPrint.DataSource = data;
        grdHideOnPrint.DataBind();
    }
}

This example should help you understand how to implement a similar functionality in your project.

Answer №2

To remove the element, you can simply add display:none in your existing JavaScript before the print statement.

Additionally, if it is a server-side control, you can use the ClientID property. However, be cautious of potential issues that may arise depending on when in the event chain you check the ClientID.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Facing problem with Rotativa on live server while trying to generate PDFs with custom templates

In the process of developing an enterprise application in C# .NET, numerous PDF documents are being generated within the system. The handling of these PDF files is managed using Rotativa. One particular PDF file utilizes a user-created template in the syst ...

attempting to fulfil a promise through a resolution

I am currently attempting to use a resolve with a promise in response to an issue with filters that I am currently tackling. However, my resolve function is not yet functioning as expected. I have decided to implement this approach based on advice I recei ...

The Console's OutputEncoding was properly configured, but it continued to display nonsensical characters

Why do Visual Studio and System.Console use different encodings for characters? How can I make the console's encoding match that of Visual Studio? Despite various posts on this issue, a clear solution seems to be missing. Below are all the options I ...

Ways to invoke a child component's function in React Native

I need to invoke a component function from a sibling component and I've opted to do it through the parent component and refs. Here's my parent component SMS-Registration.js import React, {Component} from 'react'; import PhoneNumber fr ...

Is it possible to further simplify this piece of JavaScript using jQuery?

In my journey to learn and grow with Javascript, I have come across a snippet of code that simply attaches an onclick event to a button and updates the text of an em tag below it. As I delve deeper into jQuery, I am beginning to appreciate its syntax and u ...

Issue in Vuetify: The value of the first keypress event is consistently an empty string

I need to restrict the user from entering numbers greater than 100. The code snippet below represents a simplified version of my production code. However, I am facing an issue where the first keypress always shows an empty string result. For example, if ...

How can I add color to arrow icons in tabulator group rows?

Is there a way to specify the color of the arrows in collapsed/expanded group rows? Also, what CSS code should I use to define the font color for column group summaries? You can view an example of what I am trying to customize here: https://jsfiddle.net/s ...

Setting up dependency injection with self-hosted MVC 4 API controllers

Despite reviewing all related questions on SO, my problem still persists, so I've decided to create a new question for it. I'm facing an issue with a unit test that involves referencing another project containing an MVC 4 ApiController which has ...

Is there a way for me to directly download the PDF from the API using Angular?

I'm trying to download a PDF from an API using Angular. Here's the service I've created to make the API call: getPDF(id:any) { return this.http.get( `url?=${id}`, { responseType: 'blob' as 'json', obs ...

Developing Attributes in JSON

Greetings stackOverflow Community, I'm struggling a bit with creating JSON objects. I have code snippet that is meant to populate a list called members with names, and then add a property to each of those names. Here is the specific snippet in questi ...

What is the best way to repeatedly add a single Panel instance to a FlowLayoutPanel in a C# desktop application?

In my project, I want to add a single instance of a Panel multiple times to a single FlowLayoutPanel. This way, making changes to the background color of one Panel instance will reflect on all views. ...

Can you tell me the proper term for the element that allows CSS properties to be changed after a link has been clicked?

I have integrated a horizontal scrolling date selector on my website, and it is functioning well. However, I am facing an issue while trying to change the CSS properties of a clicked date link using jQuery. Despite successfully firing the click event, I am ...

Errors occurring during the building process in NextJS within the __webpack_require__ function

I am currently in the process of migrating a website from React-Fuse to NextJS with React. Everything is working smoothly except for an error that keeps popping up when I try to create a build: > Build error occurred TypeError: Cannot read property &apo ...

Issue: Unable to locate module - Error in integration of Vue.js with Laravel framework

I'm currently following a tutorial on YouTube for setting up Vue and Laravel. My resources folder structure looks like this so far: - resources - js - app.js - vue -app.vue In my app.js file: require('./bootstrap&ap ...

vue-router: error encountered while attempting to load asynchronous component for rendering

I'm new to vue-router and having trouble getting it to work. When I try to start my app, these errors pop up: [vue-router] Failed to resolve async component render: TypeError: _vm is undefined 49:16:39 [vue-router] uncaught error during route navigat ...

Best practices for utilizing the Cast() and OfType() methods in Linq

Exploring the various techniques for converting types to IEnumerable from an Arraylist in Linq raises questions about when each method should be utilized. For example: IEnumerable<string> someCollection = arrayList.OfType<string>() versus I ...

Concentrating on the open window monitored by $window

I need to launch multiple windows from my angular application. What I want is to give the user the option to click a button on the main page in order to bring one of these windows back into focus. Typically, in JavaScript, I would accomplish this using the ...

Issue with NODE.JS: ffmpeg not detected when utilizing Audioconcat module

Need help concatenating two audio files. I tried using an npm package called audioconcat, but when I implemented the code below, I encountered the following error: Error: Error: Cannot find ffmpeg at E:\VoiceMan\registercheck\node_modul ...

Is it possible to invoke a function within a useState hook and access its resulting data?

Currently, I am facing the challenge of fetching an object from a server and utilizing its variables in another function to render them. This specific task pertains to a React project for my school assignment. In previous iterations, I was able to retrieve ...

Synchronizing jQuery parameters

I have developed a JavaScript shopping basket where the total sum updates automatically when a quantity is selected. However, I encountered an issue where the total value does not update when a product is removed unless the page is refreshed. Here's ...