Validate Date entered into a DataGridView - c#

I am trying to validate an entered Date value in a DataGridViewCell by users and if the value does not match the a specific scheme, it should give the user a message like
entered value should match dd/MM/yyyy format
I tried below code on CellValidating event
private void DGV_PatientSessions_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
{
if (DGV_PatientSessions.Columns[e.ColumnIndex].Name == "DGV_PatientSessions_Date")
{
string DateValue;
DateTime DateFormated;
DateValue = DGV_PatientSessions.CurrentRow.Cells["DGV_PatientSessions_Date"].Value.ToString();
if (DateTime.TryParseExact(DateValue, "dd/MM/yyyy", new CultureInfo("ar-SY"), DateTimeStyles.None, out DateFormated))
{
MessageBox.Show("done");
}
}
}
but I still get message error below
I tried to use regex which not recommended as I found when I searched but it wont work
string DateFormat;
DateFormat = DGV_PatientSessions.CurrentRow.Cells["DGV_PatientSessions_Date"].Value.ToString();
if(Regex.IsMatch(DateFormat, #"(0[1-9]|[12][0-9]|3[01])[- /.](0[1-9]|1[012])[- /.](19|20)\d\d$"))
{
MessageBox.Show("done");
}
else
{
MessageBox.Show("value should match dd/MM/yyyy format);
}

You need to cancel the edit if the data entered is not valid using e.Cancel = true;:
private void DGV_PatientSessions_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
{
if (DGV_PatientSessions.Columns[e.ColumnIndex].Name == "DGV_PatientSessions_Date")
{
string DateValue;
DateTime DateFormated;
DateValue = DGV_PatientSessions.CurrentRow.Cells["DGV_PatientSessions_Date"].Value.ToString();
if (DateTime.TryParseExact(DateValue, "dd/MM/yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out DateFormated))
{
MessageBox.Show("done");
}
else
{
MessageBox.Show("value should match dd/MM/yyyy format");
e.Cancel = true; // The important part
}
}
}

Related

How to validate textbox value while user enters and display error message?

So, I have to code for a method that validates whether the string that saves name contains alphabets only, no numbers. The validation of textbox values should apply when the user enters by textchanged event before submitting the form and display an error message of red color on the label. My code works but the problem is when I enter a numeric number in text box, the label displays error which stays even when I delete the text box value and enter the alphabetic string.
I have declared a method which assign error string to label, and is called if regular expression does not match with the text box input, during text changed event.
public void Validator()
{
Calculate_Salary.Enabled = false;
label4.Text = "Please enter only alphabetical letters";
}
private void _Name_TextChanged(object sender, EventArgs e)
{
Regex pattern = new Regex("/^[A-Za-z]+$/");
string name = _Name.Text;
if (pattern.IsMatch(name))
{
Calculate_Salary.Enabled = true;
label4.Text = "";
}
else
{
Validator();
}
}
Just clear the textbox before you validate:
public void Validator()
{
Calculate_Salary.Enabled = false;
label4.Text = "Please enter only alphabetical letters";
}
private void _Name_TextChanged(object sender, EventArgs e)
{
label4.Text = "";
Regex pattern = new Regex("/^[A-Za-z]+$/");
string name = _Name.Text;
if (pattern.IsMatch(name))
{
Calculate_Salary.Enabled = true;
}
else
{
Validator();
}
}
Your Regex comparison is wrong try this code:
public void Validator()
{
Calculate_Salary.Enabled = false;
label4.Text = "Please enter only alphabetical letters";
}
private void _Name_TextChanged(object sender, EventArgs e)
{
label4.Text = "";
string name = _Name.Text;
if (Regex.IsMatch(name, #"^[a-zA-Z]+$"))
Calculate_Salary.Enabled = true;
else
Validator();
}
I changed the validation code. It seems to work now.
private void _Name_TextChanged(object sender, EventArgs e)
{
label4.Text = string.Empty;
string name = _Name.Text;
if (Regex.IsMatch(_Name.Text, "^[a-zA-Z]+$") || _Name.Text=="")
{
Calculate_Salary.Enabled = true;
}
else
{
Calculate_Salary.Enabled = false;
label4.Text = Validator();
}
}

Clear the DateTimePicker control in c# winfoms

I want to clear the DateTimePicker control value when i click on clear button but i can't do that with simple double qoutes, So please help me
tbAddress.Text = "";
dtpBirth.Value = "";
cBoxGender.SelectedIndex = -1;
This should do the trick
dtpBirth.CustomFormat = " ";
dtpBirth.Format = DateTimePickerFormat.Custom;
it will clear the input box.
try is
dateTimePickerDOB.Value = DateTimePicker.MinimumDateTime
in this your date and time going to be minimum date and time in your DateTimePicker and dateTimePickerDOB mean your Design(name)
or
try this for clear the date
dateTimePicker_dob.Text = string.Empty;
in here dateTimePickerDOB mean your Design(name)
The DateTimePicker.Value is from type DateTime and not a String.
dtpBirth.Value = DateTime.Now;
You can do this:
private void DateTimePicker1_ValueChanged(object sender, EventArgs e)
{
if (dateTimePicker1.Value == DateTimePicker.MinimumDateTime)
{
dateTimePicker1.Value = DateTime.Now; // This is required in order to show current month/year when user reopens the date popup.
dateTimePicker1.Format = DateTimePickerFormat.Custom;
dateTimePicker1.CustomFormat = " ";
}
else
{
dateTimePicker1.Format = DateTimePickerFormat.Short;
}
}
private void Clear_Click(object sender, EventArgs e)
{
dateTimePicker1.Value = DateTimePicker.MinimumDateTime;
}

ASP.NET increase & decrease date by clicking image

I want to increase & decrease date on Image click like this. '<' for decrease and '>' for increment and show them in textbox. I tried like following code but not working
kindly help me to do so
protected void ImageButtonNextDate_Click(object sender, ImageClickEventArgs e)
{
DateTime date = DateTime.Now;
DateTime nextday = date.AddDays(1);
txtDate.Text = nextday.ToShortDateString();
}
protected void ImageButtonPrevDate_Click(object sender, ImageClickEventArgs e)
{
DateTime date = DateTime.Now;
DateTime nextday = date.AddDays(-1);
txtDate.Text = nextday.ToShortDateString();
}
Every time you handle click event on your images, you create a new date variable with value equal to current date. You need to store data between clicks somehow, so that it's retained for the next event. There are multiple ways to do so, for example, session variables:
protected void ImageButtonPrevDate_Click(object sender, ImageClickEventArgs e)
{
DateTime date = Session["MyDateVariable"] as DateTime ?? DateTime.Now;
DateTime nextday = date.AddDays(-1);
Session["MyDateVariable"] = nextday;
txtDate.Text = nextday.ToShortDateString();
}
I think you need to get the current value from the txtDate, then perform the logic.
protected void ImageButtonNextDate_Click(object sender, ImageClickEventArgs e)
{
txtDate.Text = (Convert.ToDateTime(txtDate.Text).AddDays(1)).ToShortDateString();
}
protected void ImageButtonPrevDate_Click(object sender, ImageClickEventArgs e)
{
txtDate.Text = (Convert.ToDateTime(txtDate.Text).AddDays(-1)).ToShortDateString();
}
UPDATE
You only need to load the value of DateTime.Now to txtDate on first page load, on every post back, do not set it.
if(!IsPostBack()){
txtDate.Text = DateTime.Now.ToShortDateString();
}

Disable all dates after some months from a certain date Android DatePicker

I have two DatePickers in my app. First, shows the FromDate which is CurrentDate+1, the second shows the ToDate ie. FromDate+1.
I have got the above scenario working. But now I want to disable all the dates after 6 months from the FromDate.
I tried doing the following,but the calender then shows 01/01/1970 as the current date.
BookingActivity.cs
void IbtnToDate_Click(object sender, EventArgs e)
{
toDateClicked = true;
fromDateClicked = false;
dateFragment = new DatePickerFragment(this, DateTime.Parse (editFromDate.Text.ToString ()).AddDays (1), this, DateTime.Parse (editFromDate.Text.ToString ()));
dateFragment.Show(FragmentManager, null);
}
void IbtnFromDate_Click(object sender, EventArgs e)
{
fromDateClicked = true;
toDateClicked = false;
dateFragment = new DatePickerFragment(this, date.AddDays (1), this, date.AddDays (1));
dateFragment.Show(FragmentManager, null);
}
public void OnDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth)
{
var date1 = new DateTime(year, monthOfYear + 1, dayOfMonth);
if (fromDateClicked)
UpdateFromDate (date1);
else if (toDateClicked) {
UpdateToDate (date1);
}
}
DatePickerFragment.cs
public class DatePickerFragment : DialogFragment
{
private readonly Context _context;
private DateTime _date, _minDate, _maxDate;
private readonly Android.App.DatePickerDialog.IOnDateSetListener _listener;
public DatePickerFragment(Context context, DateTime date, Android.App.DatePickerDialog.IOnDateSetListener listener, DateTime minDate)
{
_context = context;
_date = date;
_listener = listener;
_minDate = minDate;
}
public override Dialog OnCreateDialog(Bundle savedState)
{
var dialog = new Android.App.DatePickerDialog(_context, _listener, _date.Year, _date.Month - 1, _date.Day);
dialog.DatePicker.MinDate =_minDate.AddDays (1).Millisecond;
dialog.DatePicker.MaxDate = _date.AddMonths(6).Millisecond;
return dialog;
}
}
How can I achieve it? Any help would be appreciated.
You can use setMaxDate and can do something like:
1- Get the date from _mindate string:
String dateString = "03/26/2012";
SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
Date convertedDate = new Date();
try {
convertedDate = dateFormat.parse(dateString);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
2- Get date of 6 months from min_date:
Calendar cal = GregorianCalendar.getInstance();
cal.setTime(convertedDate);
cal.add(Calendar.MONTH, 1);
Date 6MonthsFromCurrentDate = cal.getTime();
3- Restricting the datePicker to that date:
datePickerDialog.getDatePicker().setMaxDate(6MonthsFromCurrentDate.getTime());
Use these lines of code.
Calendar ci = Calendar.getInstance();
String CiDateTime = ci.get(Calendar.YEAR) + "-" +
(ci.get(Calendar.MONTH) + 7) + "-" + //for 6 month future
ci.get(Calendar.DAY_OF_MONTH);
SimpleDateFormat f = new SimpleDateFormat("dd-MMM-yyyy");
Date d;
try {
d = f.parse(CiDateTime);
long milliseconds = d.getTime();
_date.setMaxDate(milliseconds);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

Convert string to Date format

my string is as follows:
string s ="20000101";
I would like to convert it to Date format. How can I do it?
Assuming you are using C# and .Net you will want to use DateTime.ParseExact or DateTime.TryParseExact. The format string is most likely "yyyyMMdd".
var datestring = "20000101";
var date1 = DateTime.ParseExact(datestring, "yyyyMMdd", null);
or
DateTime dateResult;
if (!DateTime.TryParseExact(datestring, "yyyyMMdd",
null, DateTimeStyles.AssumeLocal,
out dateResult))
dateResult = DateTime.MinValue; //handle failed conversion here
in C/C++, use the time.h (ctime) library's gmtime function, after converting the time to an integer: tm =gmtime(atoi(time_string));
If C#/.NET, use DateTime.Parse. If Java, use DateFormat.parse
use this to convert time
using System; using System.Collections.Generic; using
System.ComponentModel; using System.Data; using System.Drawing; using
System.Text; using System.Windows.Forms;
namespace DateTimeConvert {
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
label1.Text= ConvDate_as_str(textBox1.Text);
}
public string ConvDate_as_str(string dateFormat)
{
try
{
char[] ch = dateFormat.ToCharArray();
string[] sps = dateFormat.Split(' ');
string[] spd = sps[0].Split('.');
dateFormat = spd[0] + ":" + spd[1]+" "+sps[1];
DateTime dt = new DateTime();
dt = Convert.ToDateTime(dateFormat);
return dt.Hour.ToString("00") + dt.Minute.ToString("00");
}
catch (Exception ex)
{
return "Enter Correct Format like <5.12 pm>";
}
}
private void button2_Click(object sender, EventArgs e)
{
label2.Text = ConvDate_as_date(textBox2.Text);
}
public string ConvDate_as_date(string stringFormat)
{
try
{
string hour = stringFormat.Substring(0, 2);
string min = stringFormat.Substring(2, 2);
DateTime dt = new DateTime();
dt = Convert.ToDateTime(hour+":"+min);
return String.Format("{0:t}", dt); ;
}
catch (Exception ex)
{
return "Please Enter Correct format like <0559>";
}
}
} }

Categories