Solved

Validating Date and Time inside Datagridview in C#

Posted on 2016-10-06
4
28 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

Netscaler Common Configuration How To guides

If you use NetScaler you will want to see these guides. The NetScaler How To Guides show administrators how to get NetScaler up and configured by providing instructions for common scenarios and some not so common ones.

Question has a verified solution.

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

Suggested Solutions

Entity Framework is a powerful tool to help you interact with the DataBase but still doesn't help much when we have a Stored Procedure that returns more than one resultset. The solution takes some of out-of-the-box thinking; read on!
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.
This Micro Tutorial demonstrates using Microsoft Excel pivot tables, how to reverse engineer competitors' marketing strategies through backlinks.
Two types of users will appreciate AOMEI Backupper Pro: 1 - Those with PCIe drives (and haven't found cloning software that works on them). 2 - Those who want a fast clone of their boot drive (no re-boots needed) and it can clone your drive wh…

770 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