字符串,日期时间,SQL,Gridview [英] String, DateTime, SQL, Gridview
问题描述
我一直在进行动议,但似乎仍然无法做到这一点.我在网格视图中有一个文本框,这些文本框是从Access数据库填充的.它们都是日期时间值.在后端代码中,我试图遍历所有这些值,然后应用条件格式.由于某些未知原因,我无法从网格视图中的那些文本框中获取值,当我这样做时,应用程序将它们视为字符串,而不是日期时间.相同的错误没有将字符串识别为有效的DateTime",这是徒劳的.不断弹出.
关于如何从网格视图文本框中获取值,然后将其从字符串转换为日期时间格式的任何想法?
这是到目前为止的代码.
I have been going through the motions and still cannot seem to get this right. I have text boxes in a grid view that are populated from an access database. They are all date time values. In the back-end code, I am trying to loop through all those values and then apply conditional formatting. For some unknown reason I am unable to get the value from those text boxes in the grid view and when I do, they are seen by the application as string as opposed to date time. Converting is futile as the same error, "String was not recognized as a valid DateTime." keeps popping up.
Any ideas on how to get values from a grid view text box, and then convert them from a string to a date time format?
Here is the code thus far.
var myLabel2 = (TextBox)GridView1.Rows[p].Cells[0].FindControl("Label2");
var myLabel4 = (TextBox)GridView1.Rows[p].Cells[0].FindControl("Label4");
var myLabel7 = (Label)GridView1.Rows[p].Cells[0].FindControl("Label7");
var myLabel9 = (Label)GridView1.Rows[p].Cells[0].FindControl("Label9");
string dateString = myLabel2.Text;
CultureInfo provider = CultureInfo.InvariantCulture;
string format = "dd/MMM/yyyy h:mm tt zzz";
DateTime result = DateTime.ParseExact(dateString, format, provider);
DateTime start = Convert.ToDateTime(myLabel2.Text).Date;
DateTime now = DateTime.Now.Date;
DateTime end = Convert.ToDateTime(myLabel4.Text).Date;
if (now >= start && now <= end)
{
myLabel2.BackColor = Color.Chartreuse;
myLabel4.BackColor = Color.Chartreuse;
myLabel7.BackColor = Color.Chartreuse;
myLabel9.BackColor = Color.Chartreuse;
}
else
{
myLabel2.BackColor = Color.White;
myLabel4.BackColor = Color.White;
myLabel7.BackColor = Color.White;
myLabel9.BackColor = Color.White;
}
在此先感谢您
Thanks in advance
推荐答案
检查您的语言设置.标准的英语设置为mm/dd/yyyy,并且您尝试以yyyy/mm/dd格式转换日期.
Check your language settings. The standard English settings are mm/dd/yyyy and you trying to convert a date in the format yyyy/mm/dd.
使用Convert.ToDateTime("SomeDateString")
string dateString ="2012/04/03 12:00:00 AM";
DateTime _dt = Convert.ToDateTime(dateString);
Use Convert.ToDateTime("SomeDateString")
string dateString = "2012/04/03 12:00:00 AM";
DateTime _dt = Convert.ToDateTime(dateString);
我不确定您的问题是什么.试试这个,它可以工作:
I''m not sure what your problem is. Try this, it works:
DateTime t1 = DateTime.Now.AddDays(1).Date;
DateTime t2 = DateTime.Now.Date;
DateTime t3 = DateTime.Now.AddDays(-1).Date;
if (t1 > t2 && t2 > t3)
{
Console.WriteLine("It worked");
}
我认为您没有检查日期以查看它们是否符合您的预期格式.可能是您采用了其他格式.
I would think you did not check the dates to see if they were in the format you expected. Could be you were assuming some other format.
这篇关于字符串,日期时间,SQL,Gridview的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!