Solved

Validating Date and Time inside Datagridview in C#

Posted on 2016-10-06
4
22 Views
Last Modified: 2016-11-28
Dear Sir/Madam,

Please be kind enough tell me how I can validate Date and Time in datagridview as I enter the data.

Any help would be greatly appreciated.

Kind Regards,
Indunil Sanjeewa
0
Comment
  • 2
4 Comments
 
LVL 33

Expert Comment

by:it_saige
ID: 41832024
Just to clarify, do you mean as you enter data into a text field that is part of the datagridview row you want to validate it?  Or, do you mean that as you insert rows, you want to validate the cell value associated with the column that contains the date time value?

-saige-
0
 

Author Comment

by:Indunil Sanjeewa Amarasinghe
ID: 41832071
I basically need to have a time picker and a date picker in two columns separately not both time and date.

Kind Regards,
Indunil Sanjeewa
0
 
LVL 33

Accepted Solution

by:
it_saige earned 500 total points
ID: 41832501
You could try something like this:

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

namespace EE_Q28974717
{
	public partial class Form1 : Form
	{
		bool IsSendingKeys = false;

		public Form1()
		{
			InitializeComponent();
		}

		protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
		{
			switch (keyData & Keys.KeyCode)
			{
				case Keys.Enter:
				case Keys.Tab:
					dataGridView1.Focus();
					break;
			}
			return base.ProcessCmdKey(ref msg, keyData);
		}

		private void OnLoad(object sender, EventArgs e)
		{
			dataGridView1.DataSource = (from i in Enumerable.Range(0, 10) select new { ID = i, FirstName = string.Format("FirstName{0}", i), StartDate = DateTime.MinValue, StartTime = DateTime.MinValue, EndDate = DateTime.MinValue, EndTime = DateTime.MinValue }).ToList();
		}

		private void OnCellClick(object sender, DataGridViewCellEventArgs e)
		{
			if (sender is DataGridView)
			{
				var grid = sender as DataGridView;
				if (grid.Rows.Count > 0)
				{
					var dtp = default(DateTimePicker);
					var columns = new[] { "startdate", "starttime", "enddate", "endtime" };
					var column = grid.Columns[e.ColumnIndex].Name;
					if (columns.Any(x => x.Equals(column, StringComparison.OrdinalIgnoreCase)))
					{
						dtp = new DateTimePicker();
						grid.Controls.Add(dtp);
						dtp.Format = column.IndexOf("time", StringComparison.OrdinalIgnoreCase) > -1 ? DateTimePickerFormat.Time : DateTimePickerFormat.Short;
						if (dtp.Format.Equals(DateTimePickerFormat.Time))
							dtp.ShowUpDown = true;
						var rectangle = grid.GetCellDisplayRectangle(e.ColumnIndex, e.RowIndex, true);
						dtp.Size = new Size(rectangle.Width, rectangle.Height);
						dtp.Location = new Point(rectangle.X, rectangle.Y);
						//dtp.CloseUp += OnCloseUp;
						dtp.Leave += OnLeave;
						dtp.Validating += OnValidating;
						dtp.Visible = true;
					}
				}
			}
		}

		private void OnCellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
		{
			if (sender is DataGridView)
			{
				var grid = sender as DataGridView;
				if (grid.Rows.Count > 0)
				{
					var columns = new[] { "startdate", "starttime", "enddate", "endtime" };
					var column = grid.Columns[e.ColumnIndex].Name;
					if (columns.Any(x => x.Equals(column, StringComparison.OrdinalIgnoreCase)))
						e.Value = ((DateTime)e.Value).ToString(column.IndexOf("time", StringComparison.OrdinalIgnoreCase) > -1 ? "hh:mm tt" : "MM/dd/yyyy");
				}
			}
		}

		private void OnLeave(object sender, EventArgs e)
		{
			if (sender is DateTimePicker)
			{
				var dtp = sender as DateTimePicker;
				if (dtp != null && !string.IsNullOrEmpty(dtp.Text))
				{
					try
					{
						IsSendingKeys = true;
						SendKeys.SendWait("{RIGHT}");
						SendKeys.SendWait("{LEFT}");
					}
					finally
					{
						IsSendingKeys = false;
					}
				}
				dtp.Visible = false;
			}
		}

		private void OnValidating(object sender, EventArgs e)
		{
			if (sender is DateTimePicker)
			{
				var dtp = sender as DateTimePicker;
				var grid = dtp.Parent as DataGridView;
				if (grid.Rows.Count > 0)
				{
					var row = grid.Rows[grid.CurrentCell.RowIndex];
					if (row.DataBoundItem != null)
					{
						var data = row.DataBoundItem.Cast(new { ID = -1, FirstName = "", StartDate = DateTime.MinValue, StartTime = DateTime.MinValue, EndDate = DateTime.MinValue, EndTime = DateTime.MinValue });
						var flags = BindingFlags.NonPublic | BindingFlags.Instance;
						var formats = new[] { "<{0}>i__Field", "<{0}>" };
						foreach (var property in data.GetType().GetProperties())
						{
							if (property.Name.Equals(grid.Columns[grid.CurrentCell.ColumnIndex].Name, StringComparison.OrdinalIgnoreCase))
							{
								var names = formats.Select(x => string.Format(x, property.Name)).ToList();
								var field = data.GetType().GetFields(flags).First(f => names.Contains(f.Name));
								if (field != null)
									field.SetValue(data, dtp.Value);
							}
						}
					}
				}
				dtp.Visible = false;
			}
		}
	}

	static class Extensions
	{
		public static T Cast<T>(this object obj, T type)
		{
			return (T)obj;
		}
	}
}

Open in new window

Form1.Desinger.cs -
namespace EE_Q28974717
{
	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();
			((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).BeginInit();
			this.SuspendLayout();
			// 
			// dataGridView1
			// 
			this.dataGridView1.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
			this.dataGridView1.Dock = System.Windows.Forms.DockStyle.Fill;
			this.dataGridView1.Location = new System.Drawing.Point(0, 0);
			this.dataGridView1.Name = "dataGridView1";
			this.dataGridView1.Size = new System.Drawing.Size(531, 290);
			this.dataGridView1.TabIndex = 0;
			this.dataGridView1.CellClick += new System.Windows.Forms.DataGridViewCellEventHandler(this.OnCellClick);
			this.dataGridView1.CellFormatting += new System.Windows.Forms.DataGridViewCellFormattingEventHandler(this.OnCellFormatting);
			// 
			// Form1
			// 
			this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
			this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
			this.ClientSize = new System.Drawing.Size(531, 290);
			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;
	}
}

Open in new window

Which produces the following output -

Initial load:Capture.JPGChanging the start date:Capture.JPGTabbing to the next column after the change:Capture.JPGChanging the start time:Capture.JPGTabbing to the next column after the change:Capture.JPG
-saige-
2
 
LVL 14

Expert Comment

by:frankhelk
ID: 41903872
No comment has been added to this question in more than 21 days, so it is now classified as abandoned.

I have recommended this question be closed as follows:

Accept: it_saige (https:#a41832501)

If you feel this question should be closed differently, post an objection and the moderators will review all objections and close it as they feel fit. If no one objects, this question will be closed automatically the way described above.

frankhelk
Experts-Exchange Cleanup Volunteer
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

Introduction This article series is supposed to shed some light on the use of IDisposable and objects that inherit from it. In essence, a more apt title for this article would be: using (IDisposable) {}. I’m just not sure how many people would ge…
Exception Handling is in the core of any application that is able to dignify its name. In this article, I'll guide you through the process of writing a DRY (Don't Repeat Yourself) Exception Handling mechanism, using Aspect Oriented Programming.
I designed this idea while studying technology in the classroom.  This is a semester long project.  Students are asked to take photographs on a specific topic which they find meaningful, it can be a place or situation such as travel or homelessness.…
This is a video that shows how the OnPage alerts system integrates into ConnectWise, how a trigger is set, how a page is sent via the trigger, and how the SENT, DELIVERED, READ & REPLIED receipts get entered into the internal tab of the ConnectWise …

919 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

15 Experts available now in Live!

Get 1:1 Help Now