Solved

c# Clearing Column Headers in a datagridview

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

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

Highfive + Dolby Voice = No More Audio Complaints!

Poor audio quality is one of the top reasons people don’t use video conferencing. Get the crispest, clearest audio powered by Dolby Voice in every meeting. Highfive and Dolby Voice deliver the best video conferencing and audio experience for every meeting and every room.

Join & Write a Comment

In an ASP.NET application, I faced some technical problems. In this article, I list them out and show the solutions that I found.  I hope it will be useful. Problem: After closing a pop-up window, the parent page should be refreshed automaticall…
It was really hard time for me to get the understanding of Delegates in C#. I went through many websites and articles but I found them very clumsy. After going through those sites, I noted down the points in a easy way so here I am sharing that unde…
This video gives you a great overview about bandwidth monitoring with SNMP and WMI with our network monitoring solution PRTG Network Monitor (https://www.paessler.com/prtg). If you're looking for how to monitor bandwidth using netflow or packet s…
This video explains how to create simple products associated to Magento configurable product and offers fast way of their generation with Store Manager for Magento tool.

705 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

18 Experts available now in Live!

Get 1:1 Help Now