Go Premium for a chance to win a PS4. Enter to Win

x
?
Solved

C# CheckState of a Checkbox

Posted on 2016-08-12
14
Medium Priority
?
51 Views
Last Modified: 2016-10-17
I dynamically add a datagridview to my form.  When a user types in a number and hits 'Enter' the datagridview is created and populated.  I also add a checkbox in the column header so the user can toggle between checking and unchecking all of the boxes.  My problem comes when the user clicks on the 'Clear' button.  I would like the 'Clear' button to clear the whole grid and 'Uncheck' the column header checkbox if it is checked.  Here is my problem:

  1. I 'Check' the column Header checkbox
  2. The very first time I click on the 'Clear' button the column header checkbox is unchecked
  3. I 'Check the column Header checkbox a 2nd time
  4. I click on the 'Clear' button a 2nd time and everything BUT the column header checkbox is cleared

When I step through my code it is already showing that the column header checkbox is 'Unchecked' when it is actually checked.  It's like the state of the checkbox never gets changed.

I am not sure what to do.  

Any help is appreciated.
0
Comment
Question by:huerita37
  • 7
  • 4
  • 2
14 Comments
 
LVL 14

Expert Comment

by:Dustin Saunders
ID: 41753893
Can you paste the current code?
0
 

Author Comment

by:huerita37
ID: 41753919
When the user types in a number in the 'Search' box this is called:
private void txtSearch_KeyUp(object sender, KeyEventArgs e)
        {
if (e == null || e.KeyCode == Keys.Enter)
            {

                //Clear the datasource and datagridview so everything is starting from scratch
                if (HeaderCheckBox != null)
                {
                    HeaderCheckBox.CheckState = CheckState.Unchecked;
                }
                dgBilling.DataSource = null;
                dgBilling.Rows.Clear();
                dgBilling.Columns.Clear();
                dgBilling.ColumnCount = 0;
                
                BindBillGrid(sSCH, sdb); 
}

Open in new window


Here is my code to create and populate the datagridview:
private void BindBillGrid(string sSCH, Boolean sdb)
        {
DataSet ds = new DataSet();

            IsLoadBillGrid = true;

            string strSQL = "My sql statement here";
 SqlConnection connection = new SqlConnection(Cm.adrl);
            SqlDataAdapter dataadapter = new SqlDataAdapter(strSQL, connection);
            connection.Open();
            dataadapter.Fill(ds);
            connection.Close();
            //Set AutoGenerateColumns False 
            dgBilling.AutoGenerateColumns = false;

            //Set Columns Count
            dgBilling.ColumnCount = 8;

            //Add Columns  
            DataGridViewCheckBoxColumn clsCol2 = new DataGridViewCheckBoxColumn();
            clsCol2.HeaderText = "";
            clsCol2.ValueType = typeof(System.Boolean);
            clsCol2.Width = 55;
            clsCol2.Name = "dgcChecked";
            clsCol2.DataPropertyName = "Checked";
            clsCol2.SortMode = DataGridViewColumnSortMode.Automatic;
            clsCol2.FalseValue = false;
            clsCol2.TrueValue = true;
            dgBilling.Columns.Insert(0, clsCol2);
            
            AddHeaderCheckBox();
            HeaderCheckBox.KeyUp += new KeyEventHandler(HeaderCheckBox_KeyUp);
            HeaderCheckBox.MouseClick += new MouseEventHandler(HeaderCheckBox_MouseClick);
            dgBilling.CellValueChanged += new DataGridViewCellEventHandler(dgBilling_CellValueChanged);
            dgBilling.CurrentCellDirtyStateChanged += new EventHandler(dgBilling_CurrentCellDirtyStateChanged);
            dgBilling.CellPainting += new DataGridViewCellPaintingEventHandler(dgBilling_CellPainting);
            
            dgBilling.Columns[1].Name = "dgcMatterID";
            dgBilling.Columns[1].HeaderText = "Matter ID";
            dgBilling.Columns[1].DataPropertyName = "matter_code";
            dgBilling.Columns[1].Width = 103;
            dgBilling.Columns[1].ReadOnly = true;
            dgBilling.Columns[1].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleLeft;

            dgBilling.Columns[2].Name = "dgcDescription";
            dgBilling.Columns[2].HeaderText = "Description";
            dgBilling.Columns[2].DataPropertyName = "matter_name";
            dgBilling.Columns[2].Width = 240;
            dgBilling.Columns[2].ReadOnly = true;
            dgBilling.Columns[3].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleLeft;

            dgBilling.Columns[3].Name = "dgcTranDate";
            dgBilling.Columns[3].HeaderText = "Date";
            dgBilling.Columns[3].DataPropertyName = "tran_date";
            dgBilling.Columns[3].Width = 65;
            dgBilling.Columns[3].ReadOnly = true;
            dgBilling.Columns[3].DefaultCellStyle.Format = "MM/dd/yy";
            dgBilling.Columns[3].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleLeft;

            dgBilling.Columns[4].Name = "dgcType";
            dgBilling.Columns[4].HeaderText = "Type";
            dgBilling.Columns[4].DataPropertyName = "Type";
            dgBilling.Columns[4].Width = 44;
            dgBilling.Columns[4].ReadOnly = true;
            dgBilling.Columns[4].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;

            dgBilling.Columns[5].Name = "dgcBillNo";
            dgBilling.Columns[5].HeaderText = "Bill#";
            dgBilling.Columns[5].DataPropertyName = "bill_num";
            dgBilling.Columns[5].Width = 55;
            dgBilling.Columns[5].ReadOnly = true;
            dgBilling.Columns[5].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleLeft;

            dgBilling.Columns[6].Name = "dgcBillAmt";
            dgBilling.Columns[6].HeaderText = "Bill Amt";
            dgBilling.Columns[6].DataPropertyName = "BillAmt";
            dgBilling.Columns[6].Width = 85;
            dgBilling.Columns[6].ReadOnly = true;
            dgBilling.Columns[6].DefaultCellStyle.Format = "C";
            dgBilling.Columns[6].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;

            dgBilling.Columns[7].Name = "dgcPmtAmt";
            dgBilling.Columns[7].HeaderText = "Pmt Amt";
            dgBilling.Columns[7].DataPropertyName = "PmtAmt";
            dgBilling.Columns[7].Width = 85;
            dgBilling.Columns[7].ReadOnly = true;
            dgBilling.Columns[7].DefaultCellStyle.Format = "C";
            dgBilling.Columns[7].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;

            dgBilling.Columns[8].Name = "dgcTotalAR";
            dgBilling.Columns[8].HeaderText = "A/R";
            dgBilling.Columns[8].DataPropertyName = "TOTAL_AR";
            dgBilling.Columns[8].Width = 85;
            dgBilling.Columns[8].ReadOnly = true;
            dgBilling.Columns[8].DefaultCellStyle.Format = "C";
            dgBilling.Columns[8].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;

            dgBilling.DataSource = ds.Tables[0];

            dgBilling.Size = new System.Drawing.Size(840, 417);
            tabBilling.Size = new System.Drawing.Size(840, 417);
            tabsBillingTime.Size = new System.Drawing.Size(850, 444);

            TotalCheckBoxes = 0;
            TotalCheckedCheckBoxes = 0;
            
            //Variables for HeaderCheckBox
            TotalCheckBoxes = dgBilling.RowCount;
            TotalCheckedCheckBoxes = 0;
}

Open in new window


Here is my code to clear the screen:

 private void btnClear_Click(object sender, EventArgs e)
        {
            DialogResult dResult = (DialogResult)MessageBox.Show("Are you sure you want to clear search?", "Clearing Searches - Start Empty Application  ", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
            if (dResult == DialogResult.Yes)
            {
                TotalCheckBoxes = 0;
                TotalCheckedCheckBoxes = 0;
                HeaderCheckBox.CheckState = CheckState.Unchecked;
                RowCheckBoxClick((DataGridViewCheckBoxCell)dgBilling[0, 0]);

                txtSearch.Text = "";
                txtSearch.ForeColor = System.Drawing.Color.Gray;
                txtSearch.Text = "Search By Matter ID, Description, or Client Sort";
                txtSearch_KeyUp(sender, null);
                lblMatterCreditAmt.Text = "$0.00";
                lblTrustBalanceAmt.Text = "$0.00";
                lblAOL.Text = "";
                lblClient.Text = "";
                lblReceipts.Visible = false;
                dgReceipts.Visible = false;
                lblCreditTransfer.Visible = false;
                dgCreditTransfers.Visible = false;
            }
        }

Open in new window

0
 
LVL 14

Expert Comment

by:Dustin Saunders
ID: 41753926
What does the code on your header checkbox that checks all the results look like?
0
Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

 

Author Comment

by:huerita37
ID: 41753931
private void HeaderCheckBox_MouseClick(object sender, MouseEventArgs e)
        {
            HeaderCheckBoxClick((CheckBox)sender);
        }


        private void HeaderCheckBoxClick(CheckBox HCheckBox)
        {
            IsHeaderCheckBoxClicked = true;

            foreach (DataGridViewRow Row in dgBilling.Rows)
                ((DataGridViewCheckBoxCell)Row.Cells["dgcChecked"]).Value = HCheckBox.Checked;

            dgBilling.RefreshEdit();

            TotalCheckedCheckBoxes = HCheckBox.Checked ? TotalCheckBoxes : 0;

            GetCheckedTotals();

            IsHeaderCheckBoxClicked = false;
        }

        private void RowCheckBoxClick(DataGridViewCheckBoxCell RCheckBox)
        {
            if (RCheckBox != null)
            {
                //Modifiy Counter;            
                if (Convert.ToBoolean(RCheckBox.Value) && TotalCheckedCheckBoxes < TotalCheckBoxes)
                    TotalCheckedCheckBoxes++;
                else if (TotalCheckedCheckBoxes > 0)
                    TotalCheckedCheckBoxes--;

                //Change state of the header CheckBox.
                if (TotalCheckedCheckBoxes == 0 && TotalCheckBoxes == 0)
                    HeaderCheckBox.Checked = false;
                else if (TotalCheckedCheckBoxes < TotalCheckBoxes)
                    HeaderCheckBox.Checked = false;
                else if (TotalCheckedCheckBoxes == TotalCheckBoxes)
                    HeaderCheckBox.Checked = true;

                GetCheckedTotals();
            }
        }

Open in new window

0
 

Author Comment

by:huerita37
ID: 41753933
I got the code for creating and toggling the checkboxes here:

http://www.codeproject.com/Articles/42437/Toggling-the-States-of-all-CheckBoxes-Inside-a-Dat
0
 
LVL 14

Expert Comment

by:Dustin Saunders
ID: 41753981
Instead of calling RowCheckBoxClick() do you mean to be calling HeaderCheckBoxClick() ?  The RowCheckBoxClick() looks like it's meant to run each time a checkbox other than the header is toggled.

Also this seems to be an issue:
                //Change state of the header CheckBox.
                if (TotalCheckedCheckBoxes == 0 && TotalCheckBoxes == 0)
                    HeaderCheckBox.Checked = false;
                else if (TotalCheckedCheckBoxes < TotalCheckBoxes)
                    HeaderCheckBox.Checked = false;
                else if (TotalCheckedCheckBoxes == TotalCheckBoxes)
                    HeaderCheckBox.Checked = true;

Open in new window


Because 2 of these conditions can exist at the same time.  Can it not be?
if (TotalCheckedCheckBoxes < TotalCheckBoxes)
                    HeaderCheckBox.Checked = false;
                else if (TotalCheckedCheckBoxes == TotalCheckBoxes)
                    HeaderCheckBox.Checked = true;

Open in new window

0
 

Author Comment

by:huerita37
ID: 41754060
Did you mean calling HeaderCheckBoxClick() in btnClear_Click?

If so I changed

RowCheckBoxClick((DataGridViewCheckBoxCell)dgBilling[0, 0]);
to                
HeaderCheckBoxClick((CheckBox)HeaderCheckBox);

And get the same results.  The 2nd time around the header checkbox stays checked.

You are correct when you say the two conditions can be the same but I if the two totals are 0 then I want HeaderCheckBox.Checked = false;  Otherwise HeaderCheckBox.Checked = true;
0
 

Author Comment

by:huerita37
ID: 41754144
My ultimate goal is to have a checkbox in the header of the checkbox column.  I want the user to have the ability to toggle between checking/unchecking all of the checkboxes with one click.

I found the code here to accomplish this.
http://www.codeproject.com/Articles/42437/Toggling-the-States-of-all-CheckBoxes-Inside-a-Dat

The code works great until I need to clear the grid and the header checkbox and start over with a new number.   I just need to make some changes but I am having trouble.
0
 
LVL 35

Accepted Solution

by:
it_saige earned 2000 total points
ID: 41754409
Try out this test project to see if it can provide some guidance:

Form1.cs -
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace EE_Q28963043
{
	public partial class Form1 : Form
	{
		bool isLoading = true;
		bool checkingRow = false;
		bool checkingAll = false;
		readonly List<Person> people = new List<Person>()
		{
			new Person() { ID = 1, FirstName = "John", MiddleName = "Paul", LastName = "Jones", Birthdate = new DateTime(1972, 1, 23) },
			new Person() { ID = 2, FirstName = "Craig", MiddleName = "The", LastName = "List", Birthdate = new DateTime(1994, 3, 18) },
			new Person() { ID = 3, FirstName = "Peter", MiddleName = "James", LastName = "Tyler", Birthdate = new DateTime(1988, 12, 6) },
			new Person() { ID = 4, FirstName = "Mike", MiddleName = "Douglas", LastName = "Beals", Birthdate = new DateTime(1962, 2, 12) },
			new Person() { ID = 5, FirstName = "Seymour", MiddleName = "Anthony", LastName = "Niles", Birthdate = new DateTime(1917, 7, 4) }
		};

		public Form1()
		{
			InitializeComponent();
		}

		private void OnCellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
		{
			if (sender is DataGridView)
			{
				var grid = sender as DataGridView;
				var row = grid.Rows[e.RowIndex];
				var column = grid.Columns[e.ColumnIndex];

				if (column.Equals(grid.Columns["Selector"]))
					row.DefaultCellStyle.BackColor = ((row.Cells[column.Index].Value != null && !row.Cells[column.Index].Value.Equals(DBNull.Value)) ? (bool)row.Cells[column.Index].Value : false) ? Color.Yellow : Color.White;
			}
		}

		private void OnCellMouseUp(object sender, DataGridViewCellMouseEventArgs e)
		{
			if (sender is DataGridView)
			{
				var grid = sender as DataGridView;
				var column = grid.Columns[e.ColumnIndex];

				if (column.Equals(grid.Columns["Selector"]))
					grid.EndEdit();
			}
		}

		private void OnCellValueChanged(object sender, DataGridViewCellEventArgs e)
		{
			checkingRow = true;
			if (sender is DataGridView)
			{
				var grid = sender as DataGridView;
				var row = grid.Rows[e.RowIndex];
				var column = grid.Columns[e.ColumnIndex];

				if (column.Equals(grid.Columns["Selector"]))
					row.Selected = (bool)row.Cells[column.Index].Value;

				if (!checkingAll)
					(grid.Controls.Find("cbSelector", true)[0] as CheckBox).Checked = (grid.Rows.Cast<DataGridViewRow>().Where(r => r.Cells[column.Index].Value != null && !r.Cells[column.Index].Value.Equals(DBNull.Value) && (bool)r.Cells[column.Index].Value).Count() == grid.Rows.Count);

				grid.ClearSelection();
				grid.EndEdit();
			}
			checkingRow = false;
		}

		private void OnCheckedChanged(object sender, EventArgs e)
		{
			checkingAll = true;
			if (sender is CheckBox && !checkingRow)
			{
				var cb = sender as CheckBox;
				foreach (DataGridViewRow row in dgvData.Rows)
				{
					row.Cells["Selector"].Value = cb.Checked;
					row.Selected = cb.Checked;
				}
			}
			checkingAll = false;
		}

		private void OnClick(object sender, EventArgs e)
		{
			if (sender is Button)
			{
				var btn = sender as Button;
				if (btn.Equals(btnClear))
				{
					if (dgvData.DataSource != null && dgvData.DataSource is DataTable)
					{
						var data = (dgvData.DataSource as DataTable).Rows.OfType<DataRow>().Select(row => new Person()
						{
							ID = row.Field<int>("ID"),
							FirstName = row.Field<string>("FirstName"),
							MiddleName = row.Field<string>("MiddleName"),
							LastName = row.Field<string>("LastName"),
							Birthdate = row.Field<DateTime>("Birthdate")
						}).ToList();
						dgvData.DataSource = null;
						data.Clear();
						dgvData.DataSource = data.ConvertToDataTable(true);
						(dgvData.Controls.Find("cbSelector", true)[0] as CheckBox).Checked = false;
					}
				}
				else if (btn.Equals(btnFill))
				{
					if (dgvData.DataSource != null && dgvData.DataSource is DataTable)
					{
						var data = (dgvData.DataSource as DataTable).Rows.OfType<DataRow>().Select(row => new Person()
						{
							ID = row.Field<int>("ID"),
							FirstName = row.Field<string>("FirstName"),
							MiddleName = row.Field<string>("MiddleName"),
							LastName = row.Field<string>("LastName"),
							Birthdate = row.Field<DateTime>("Birthdate")
						}).ToList();
						dgvData.DataSource = null;
						data.AddRange(from i in Enumerable.Range((data.Count > 0) ? data.Last().ID + 1 : 0, 20) select new Person() { ID = i, FirstName = string.Format("FirstName{0}", i), MiddleName = string.Format("MiddleName{0}", i), LastName = string.Format("LastName{0}", i), Birthdate = DateTime.Now.AddYears(-(9 * i)) });
						dgvData.DataSource = data.ConvertToDataTable(true);
					}
				}
				else if (btn.Equals(btnRemove))
				{
					if (dgvData.DataSource != null && dgvData.DataSource is DataTable)
					{
						var data = (dgvData.DataSource as DataTable).Rows.OfType<DataRow>().Select(row => new Person()
						{
							ID = row.Field<int>("ID"),
							FirstName = row.Field<string>("FirstName"),
							MiddleName = row.Field<string>("MiddleName"),
							LastName = row.Field<string>("LastName"),
							Birthdate = row.Field<DateTime>("Birthdate")
						}).ToList();
						Person person = default(Person);
						foreach (DataGridViewRow row in dgvData.Rows.Cast<DataGridViewRow>().Reverse())
						{
							if (row.Cells["Selector"].Value != null && !row.Cells["Selector"].Value.Equals(DBNull.Value)? (bool)row.Cells["Selector"].Value : false)
							{
								person = data.FirstOrDefault(p => p.ID.Equals(row.Cells["ID"].Value));
								if (person != null)
									data.Remove(person);
							}
						}
						dgvData.DataSource = null;
						dgvData.DataSource = data.ConvertToDataTable(true);

						if (dgvData.Rows.Cast<DataGridViewRow>().Count() == 0)
							(dgvData.Controls.Find("cbSelector", true)[0] as CheckBox).Checked = false;
					}
				}
			}
		}

		private void OnColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
		{
			if (sender is DataGridView)
			{
				var grid = sender as DataGridView;
				var newColumn = grid.Columns[e.ColumnIndex];
				var oldColumn = grid.SortedColumn;
				var direction = default(ListSortDirection);

				if (oldColumn != null)
				{
					if (oldColumn.Equals(newColumn) && grid.SortOrder == SortOrder.Descending)
						direction = ListSortDirection.Ascending;
					else
					{
						direction = ListSortDirection.Descending;
						oldColumn.HeaderCell.SortGlyphDirection = SortOrder.None;
					}
				}
				else
					direction = ListSortDirection.Descending;

				grid.Sort(newColumn, direction);
				newColumn.HeaderCell.SortGlyphDirection = (direction == ListSortDirection.Descending) ? SortOrder.Descending : SortOrder.Ascending;
			}
		}

		private void OnDataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
		{
			if (sender is DataGridView)
			{
				var grid = sender as DataGridView;
				if (grid.Rows.Count > 0)
					grid.BeginEdit(true);
				foreach (DataGridViewColumn column in grid.Columns)
				{
					if (column.Name.Equals("Selector"))
					{
						try
						{
							column.Width = 25;
							Rectangle rectangle = grid.GetCellDisplayRectangle(column.Index, -1, true);
							rectangle.X = rectangle.Location.X + (rectangle.Width / 4);
							CheckBox selector = new CheckBox() { Name = "cbSelector", Size = new Size(18, 18), Location = rectangle.Location };
							selector.CheckedChanged += OnCheckedChanged;
							grid.Controls.Add(selector);
						}
						catch (Exception)
						{
							throw;
						}
					}
					column.SortMode = DataGridViewColumnSortMode.Programmatic;
				}

				foreach (DataGridViewRow row in grid.SelectedRows)
					row.Selected = false;
				grid.EndEdit();
			}
		}

		private void OnLoad(object sender, EventArgs e)
		{
			dgvData.DataSource = people.ConvertToDataTable(true);
			isLoading = false;
		}
	}

	class Person
	{
		public int ID { get; set; }
		public string FirstName { get; set; }
		public string MiddleName { get; set; }
		public string LastName { get; set; }
		public DateTime Birthdate { get; set; }
		public string Age { get { return string.Format("{0} Years Old", DateTime.Now.Year - Birthdate.Year); } }

		public override string ToString()
		{
			 return string.Format("{0} {1}. {2} [Age: {3}]", FirstName, MiddleName, LastName, Age);
		}
	}

	static class Extensions
	{
		public static DataTable ConvertToDataTable<T>(this IEnumerable<T> source, bool addSelectorColumn)
		{
			var properties = TypeDescriptor.GetProperties(typeof(T));
			var table = new DataTable();
			var property = default(PropertyDescriptor);

			for (int i = 0; i < properties.Count - 1; i++)
			{
				property = properties[i];
				if (property.PropertyType.IsGenericType && property.PropertyType.GetGenericTypeDefinition().Equals(typeof(Nullable)))
					table.Columns.Add(property.Name, property.PropertyType.GetGenericArguments()[0]);
				else
					table.Columns.Add(property.Name, property.PropertyType);
			}

			object[] values = new object[properties.Count - 1];
			foreach (var item in source)
			{
				for (int i = 0; i < properties.Count - 1; i++)
					values[i] = properties[i].GetValue(item);
				table.Rows.Add(values);
			}

			if (addSelectorColumn)
				table.Columns.Add("Selector", typeof(bool)).SetOrdinal(0);

			return table;
		}
	}
}

Open in new window

Form1.Designer.cs -
namespace EE_Q28963043
{
	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.dgvData = new System.Windows.Forms.DataGridView();
			this.btnClear = new System.Windows.Forms.Button();
			this.btnFill = new System.Windows.Forms.Button();
			this.btnRemove = new System.Windows.Forms.Button();
			((System.ComponentModel.ISupportInitialize)(this.dgvData)).BeginInit();
			this.SuspendLayout();
			// 
			// dgvData
			// 
			this.dgvData.AllowUserToAddRows = false;
			this.dgvData.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
			this.dgvData.Location = new System.Drawing.Point(13, 13);
			this.dgvData.Name = "dgvData";
			this.dgvData.RowHeadersVisible = false;
			this.dgvData.SelectionMode = System.Windows.Forms.DataGridViewSelectionMode.FullRowSelect;
			this.dgvData.Size = new System.Drawing.Size(444, 208);
			this.dgvData.TabIndex = 0;
			this.dgvData.CellFormatting += new System.Windows.Forms.DataGridViewCellFormattingEventHandler(this.OnCellFormatting);
			this.dgvData.CellMouseUp += new System.Windows.Forms.DataGridViewCellMouseEventHandler(this.OnCellMouseUp);
			this.dgvData.CellValueChanged += new System.Windows.Forms.DataGridViewCellEventHandler(this.OnCellValueChanged);
			this.dgvData.ColumnHeaderMouseClick += new System.Windows.Forms.DataGridViewCellMouseEventHandler(this.OnColumnHeaderMouseClick);
			this.dgvData.DataBindingComplete += new System.Windows.Forms.DataGridViewBindingCompleteEventHandler(this.OnDataBindingComplete);
			// 
			// btnClear
			// 
			this.btnClear.Location = new System.Drawing.Point(382, 227);
			this.btnClear.Name = "btnClear";
			this.btnClear.Size = new System.Drawing.Size(75, 23);
			this.btnClear.TabIndex = 2;
			this.btnClear.Text = "Clear";
			this.btnClear.UseVisualStyleBackColor = true;
			this.btnClear.Click += new System.EventHandler(this.OnClick);
			// 
			// btnFill
			// 
			this.btnFill.Location = new System.Drawing.Point(301, 226);
			this.btnFill.Name = "btnFill";
			this.btnFill.Size = new System.Drawing.Size(75, 23);
			this.btnFill.TabIndex = 1;
			this.btnFill.Text = "Fill";
			this.btnFill.UseVisualStyleBackColor = true;
			this.btnFill.Click += new System.EventHandler(this.OnClick);
			// 
			// btnRemove
			// 
			this.btnRemove.Location = new System.Drawing.Point(13, 226);
			this.btnRemove.Name = "btnRemove";
			this.btnRemove.Size = new System.Drawing.Size(141, 23);
			this.btnRemove.TabIndex = 3;
			this.btnRemove.Text = "Remove Selected";
			this.btnRemove.UseVisualStyleBackColor = true;
			this.btnRemove.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(469, 261);
			this.Controls.Add(this.btnRemove);
			this.Controls.Add(this.btnClear);
			this.Controls.Add(this.btnFill);
			this.Controls.Add(this.dgvData);
			this.Name = "Form1";
			this.Text = "Form1";
			this.Load += new System.EventHandler(this.OnLoad);
			((System.ComponentModel.ISupportInitialize)(this.dgvData)).EndInit();
			this.ResumeLayout(false);

		}

		#endregion

		private System.Windows.Forms.DataGridView dgvData;
		private System.Windows.Forms.Button btnClear;
		private System.Windows.Forms.Button btnFill;
		private System.Windows.Forms.Button btnRemove;
	}
}

Open in new window

Produces the following output -

Initial load:Capture.JPGSelecting all:Capture.JPGDeselecting an item:Capture.JPGRemoving the selected items:Capture.JPGAdding more items:Capture.JPG
Pressing clear removes all items and then sets the header checkbox to false.

-saige-
0
 

Author Comment

by:huerita37
ID: 41756625
I am new to C# and datagridviews and I am having trouble taking your example of applying it to my code.  For one I use a dataset to populate my grid.  Would that matter?
0
 
LVL 35

Expert Comment

by:it_saige
ID: 41756636
It should not matter because a DataSet contains DataTables (which I convert my list into in order to bind it to the datagridview).  The difference is that when I convert my list to a datatable, I add the selector column.

-saige-
1
 

Author Comment

by:huerita37
ID: 41757057
Unfortunately I can't figure out how to convert your code to work with how I load my datagridview.

Thank you anyway.
0
 
LVL 14

Expert Comment

by:Dustin Saunders
ID: 41830000
I tested Saige's code and it works, despite the asker having issues implementing it.  Anyone else who researches this would find the same, working answer.  I'd recommend giving Saige 500 pts for a good thorough answer.
0

Featured Post

VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

Question has a verified solution.

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

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.…
Hello there! As a developer I have modified and refactored the unit tests which was written by fellow developers in the past. On the course, I have gone through various misconceptions and technical challenges when it comes to implementation. I would…
Exchange organizations may use the Journaling Agent of the Transport Service to archive messages going through Exchange. However, if the Transport Service is integrated with some email content management application (such as an anti-spam), the admin…
Look below the covers at a subform control , and the form that is inside it. Explore properties and see how easy it is to aggregate, get statistics, and synchronize results for your data. A Microsoft Access subform is used to show relevant calcul…
Suggested Courses

916 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