比较仅具有相同年份的两个文本框。 [英] Comparing Two Text Boxes having same year only.

查看:73
本文介绍了比较仅具有相同年份的两个文本框。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我有两个文本框,其中填写了开始日期和结束日期。日期,月份可能不同但年份应相同。所以我只想放为用户验证他们应该把同一年的错误消息生成显示年份不匹配。

解决方案

试试这个..

 受保护  void  Button1_Click(对象发​​件人,EventArgs e)
{
compareDate();
}
void compareDate()
{
DateTime year1 = DateTime.Parse( 13/8/2010); // 日期格式:dd / MM / yyyy
DateTime year2 = DateTime.Parse(< span class =code-string> 9/2/2012); // 日期格式:dd / MM / yyyy

if (year1.Year!= year2.Year)
{
ScriptManager.RegisterStartupScript( this 。 Page, this .GetType(), msg alert('年份不匹配!'););
}
}


您必须先告诉用户他们必须输入的日期格式文本框(例如''dd / mm / yyyy'')。最好使用DateTimePicker控件而不是文本框,因为用户将单击并选择日期,就好像用户在文本框中输入日期一样,他们可能会犯错误。



如果让我们说你正在使用文本框,那么在使用输入的事件处理程序方法中你可以使用以下代码:



 DateTime dateTime1 = DateTime.Parse(textBox1.Text);  //  我认为用户输入dd / mm / yyyy日期格式 
DateTime dateTime2 = DateTime.parse(textBox2.Text); // 日期值的第二个输入

// 比较它们
如果(dateTime1.Year!= dateTime.Year)
{
// 某些操作
}


你可以像这样用来从文本框数据获取年份&然后可以轻松比较......



<前lang =c#> DateTime dt = < span class =code-string> xx / xx / xxxx; // 您的日期转换。 ToDate(TextBox1.Text)
int year1 = dt.Year;





谢谢

开发人员博客 [ ^ ]

Hemant Singh Rautela


Hi
I have two text boxes in which the start date and end date is to be filled.The date, month can be different but the year should be same.So i just want to put a validation for the user that they should put the same year else a error message generate showing the year is not matching.

解决方案

Try this..

protected void Button1_Click(object sender, EventArgs e)
{
    compareDate();
}
void compareDate()
{
    DateTime year1 = DateTime.Parse("13/8/2010"); //Date Format: dd/MM/yyyy
    DateTime year2 = DateTime.Parse("9/2/2012"); //Date Format: dd/MM/yyyy

    if (year1.Year != year2.Year)
    {
        ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "msg", "alert('Year is not matching!');", true);
    }
}


You have to first tell the user the format of date they will have to enter in the text box (such as ''dd/mm/yyyy''). Its best to instead use a DateTimePicker control instead of textbox because then the user will click and choose the date where as if the user enters a date in a textbox they can make a mistake.

if let''s say you are using a textbox, then in the event handler method where you are using the input you can use the following code:

DateTime dateTime1 = DateTime.Parse(textBox1.Text); //Where I suppose the user enters "dd/mm/yyyy" format of date
DateTime dateTime2 = DateTime.parse(textBox2.Text); //Second input of date value

//Comparing them
if (dateTime1.Year != dateTime.Year)
{
    //Some action
}


you can use like this for getting year from textbox data & then can compare easily...

DateTime dt = "xx/xx/xxxx";//your date Convert.ToDate(TextBox1.Text)
int year1 = dt.Year;



Thanks
Developers Blog[^]
Hemant Singh Rautela


这篇关于比较仅具有相同年份的两个文本框。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆