Solved

c# Clearing Column Headers in a datagridview

Posted on 2016-08-12
1
29 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

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
Align Buttons next to each other 2 25
ISS migration from IIS 6 to IIS 8.5 rendering problems 4 50
Why is "packages element is not declared"? 2 129
Adjust the position 3 49
User art_snob (http://www.experts-exchange.com/M_6114203.html) encountered strange behavior of Android Web browser on his Mobile Web site. It took a while to find the true cause. It happens so, that the Android Web browser (at least up to OS ver. 2.…
International Data Corporation (IDC) prognosticates that before the current the year gets over disbursing on IT framework products to be sent in cloud environs will be $37.1B.
Along with being a a promotional video for my three-day Annielytics Dashboard Seminor, this Micro Tutorial is an intro to Google Analytics API data.
Internet Business Fax to Email Made Easy - With eFax Corporate (http://www.enterprise.efax.com), you'll receive a dedicated online fax number, which is used the same way as a typical analog fax number. You'll receive secure faxes in your email, fr…

910 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

Need Help in Real-Time?

Connect with top rated Experts

23 Experts available now in Live!

Get 1:1 Help Now