Solved

c# Clearing Column Headers in a datagridview

Posted on 2016-08-12
1
40 Views
Last Modified: 2016-08-15
I need to clear the header row in my datagridview.  I have tried the following:

dgBilling.DataSource = null;
                dgBilling.Rows.Clear();
                dgBilling.Columns.Clear();
                dgBilling.ColumnCount = 0;

It clears the rows but not the column headers.

Any other suggestions?
0
Comment
Question by:huerita37
1 Comment
 
LVL 33

Accepted Solution

by:
it_saige earned 500 total points
ID: 41753917
I am fairly certain that you can simply change the visibility of the header row; e.g. -

Default.aspx -
<%@ Page Title="Home Page" Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="EE_Q28963033._Default" %>
<form id="form1" runat="server">
	<asp:GridView ID="GridView1" runat="server">
	</asp:GridView>
	<br />
	<asp:button runat="server" text="Hide Headers" OnClick="OnClick" />
</form>

Open in new window

Default.aspx.cs -
using System;
using System.Linq;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace EE_Q28963033
{
	public partial class _Default : Page
	{
		protected void Page_Load(object sender, EventArgs e)
		{
			GridView1.DataSource = (from i in Enumerable.Range(0, 5) select new { ID = i, FirstName = string.Format("FirstName{0}", i), Birthdate = DateTime.Now.AddYears(-(9 * i)), IsWorking = i % 2 == 0 });
			GridView1.DataBind();
		}

		protected void OnClick(object sender, EventArgs e)
		{
			if (GridView1.HeaderRow != null)
			{
				(sender as Button).Text = GridView1.ShowHeader ? "Hide Headers" : "Show Headers";
				GridView1.ShowHeader = !GridView1.ShowHeader;
			}
		}
	}
}

Open in new window

Default.aspx.designer.cs -
//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by a tool.
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated. 
// </auto-generated>
//------------------------------------------------------------------------------

namespace EE_Q28963033 {
    
    
    public partial class _Default {
        
        /// <summary>
        /// form1 control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.HtmlControls.HtmlForm form1;
        
        /// <summary>
        /// GridView1 control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.GridView GridView1;
    }
}

Open in new window

Produces the following output -

Initial load:Capture.JPGAfter pressing the 'Hide Headers' button:Capture.JPG
In case this is for a Windows Forms Application (because asp.net does not have a DataGridView control but rather a GridView control), the concept is the same although the verbage is different:

Form1.cs -
using System;
using System.Linq;
using System.Windows.Forms;

namespace EE_Q28963033_WFA
{
	public partial class Form1 : Form
	{
		public Form1()
		{
			InitializeComponent();
		}

		private void OnLoad(object sender, EventArgs e)
		{
			dataGridView1.DataSource = (from i in Enumerable.Range(0, 5) select new { ID = i, FirstName = string.Format("FirstName{0}", i), Birthdate = DateTime.Now.AddYears(-(9 * i)), IsWorking = i % 2 == 0 }).ToList();
		}

		private void OnClick(object sender, EventArgs e)
		{
			(sender as Button).Text = dataGridView1.ColumnHeadersVisible ? "Show Headers" : "Hide Headers";
			dataGridView1.ColumnHeadersVisible = !dataGridView1.ColumnHeadersVisible;
		}
	}
}

Open in new window

Form1.Designer.cs -
namespace EE_Q28963033_WFA
{
	partial class Form1
	{
		/// <summary>
		/// Required designer variable.
		/// </summary>
		private System.ComponentModel.IContainer components = null;

		/// <summary>
		/// Clean up any resources being used.
		/// </summary>
		/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
		protected override void Dispose(bool disposing)
		{
			if (disposing && (components != null))
			{
				components.Dispose();
			}
			base.Dispose(disposing);
		}

		#region Windows Form Designer generated code

		/// <summary>
		/// Required method for Designer support - do not modify
		/// the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{
			this.dataGridView1 = new System.Windows.Forms.DataGridView();
			this.button1 = new System.Windows.Forms.Button();
			((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).BeginInit();
			this.SuspendLayout();
			// 
			// dataGridView1
			// 
			this.dataGridView1.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
			this.dataGridView1.Location = new System.Drawing.Point(13, 13);
			this.dataGridView1.Name = "dataGridView1";
			this.dataGridView1.Size = new System.Drawing.Size(460, 207);
			this.dataGridView1.TabIndex = 0;
			// 
			// button1
			// 
			this.button1.Location = new System.Drawing.Point(362, 226);
			this.button1.Name = "button1";
			this.button1.Size = new System.Drawing.Size(111, 23);
			this.button1.TabIndex = 1;
			this.button1.Text = "Hide Headers";
			this.button1.UseVisualStyleBackColor = true;
			this.button1.Click += new System.EventHandler(this.OnClick);
			// 
			// Form1
			// 
			this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
			this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
			this.ClientSize = new System.Drawing.Size(485, 261);
			this.Controls.Add(this.button1);
			this.Controls.Add(this.dataGridView1);
			this.Name = "Form1";
			this.Text = "Form1";
			this.Load += new System.EventHandler(this.OnLoad);
			((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).EndInit();
			this.ResumeLayout(false);

		}

		#endregion

		private System.Windows.Forms.DataGridView dataGridView1;
		private System.Windows.Forms.Button button1;
	}
}

Open in new window

Produces the following output -

Initial load:Capture.JPGAfter pressing the 'Hide Headers' button:Capture.JPG-saige-
0

Featured Post

Free Tool: Postgres Monitoring System

A PHP and Perl based system to collect and display usage statistics from PostgreSQL databases.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Just a quick little trick I learned recently.  Now that I'm using jQuery with abandon in my asp.net applications, I have grown tired of the following syntax:      (CODE) I suppose it just offends my sense of decency to put inline VBScript on a…
In .NET 2.0, Microsoft introduced the Web Site.  This was the default way to create a web Project in Visual Studio 2005.  In Visual Studio 2008, the Web Application has been restored as the default web Project in Visual Studio/.NET 3.x The Web Si…
Email security requires an ever evolving service that stays up to date with counter-evolving threats. The Email Laundry perform Research and Development to ensure their email security service evolves faster than cyber criminals. We apply our Threat…
The Email Laundry PDF encryption service allows companies to send confidential encrypted  emails to anybody. The PDF document can also contain attachments that are embedded in the encrypted PDF. The password is randomly generated by The Email Laundr…

839 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question