转换ASP.NET文本框控件的.text内容,日期/时间格式 [英] Convert ASP.NET textbox control .text contents to Date/Time format

查看:1211
本文介绍了转换ASP.NET文本框控件的.text内容,日期/时间格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图插入到数据库 - 关于事件的各种详细信息。在asp.net文本框使用日历扩展(那么一点点日历弹出,并用正确格式填写日期文本框)。在我的Access数据库EVENTDATE字段类型日期/时间。我需要将文本/字符串转换为日期/时间格式

到目前为止,我已经试过这样:

VB:


 保护小组的button1_Click(发送者为对象,E作为EventArgs的)把手Button1.Click    昏暗oleDbConn作为新OleDb.OleDbConnection(ConfigurationManager.ConnectionStrings(BookMeetConnString)。ConnectionString中)
    昏暗的SqlString作为字符串=INSERT INTO活动(EVENTTITLE,EventDescription,EVENTDATE,EventCategory)值
   (@ F1,F2 @,@ F3,F4 @)
    昏暗CMD作为OleDbCommand的=新的OleDbCommand(的SqlString,oleDbConn)    昏暗strDate作为字符串= tb_eventdate.Text
    昏暗dtfi作为新System.Globalization.DateTimeFormatInfo
    dtfi.ShortDatePattern =DD / MM / YYYY
    dtfi.DateSeparator =/
    昏暗objDate为DATETIME = Convert.ToDateTime(strDate,dtfi)    cmd.CommandType = CommandType.Text
    cmd.Parameters.AddWithValue(@ F1,tb_eventtitle.Text)
    cmd.Parameters.AddWithValue(@ F2,tb_eventdescription.Text)
    cmd.Parameters.AddWithValue(@ F3,tb_eventdate.Text)
    cmd.Parameters.AddWithValue(@ F4,dd_eventcategory.Text)
    oleDbConn.Open()
    cmd.ExecuteNonQuery()
    System.Threading.Thread.Sleep(2000)
    的Response.Redirect(〜/ calendar.aspx)
结束小组


下面是我的客户方code仅供参考:


 < H1>添加一个事件< ajaxToolkit:ToolkitScriptManager
 ID =ToolkitScriptManager1
                   =服务器>
               < / ajaxToolkit:ToolkitScriptManager>
            < / H1>
            < P>事件的标题:
                < ASP:文本框ID =tb_eventtitle=服务器>< / ASP:文本框>
            &所述; / P>
            < P>事件描述:
                < ASP:文本框ID =tb_eventdescription=服务器>< / ASP:文本框>
            &所述; / P>
            < P>活动日期:
                < ASP:文本框ID =tb_eventdate=服务器>< / ASP:文本框>
                < ajaxToolkit:CalendarExtender ID =tb_eventdate_CalendarExtender=服务器
                    的TargetControlID =tb_eventdate>
                < / ajaxToolkit:CalendarExtender>
            &所述; / P>
            < P>事件类别:
                < ASP:DropDownList的ID =dd_eventcategory=服务器
                    的DataSourceID =SqlDataSource1DataTextField =CategoryTitle
                    DataValueField =CategoryTitle>
                < / ASP:DropDownList的>
            &所述; / P>
            &所述p为H.;
                < ASP:按钮的ID =Button1的=服务器文本=提交/>
            &所述; / P>


当我尝试填写表格,我收到此错误:

我的两个问题是:


  1. 什么是错的上述code和我怎么成功地使用DateTimeFormatInfo类为字符串转换为日期/时间?

  2. 在一个侧面说明,日历扩展输入日期为美国时间格式文本框(MM / DD / YYYY),我如何改变这个英国(DD / MM / YYYY)的格式(我看不见在属性对话框中这样做一个显而易见的财产?)

在此先感谢您的回答!

亚当

编辑:更新code以下:


 保护小组的button1_Click(发送者为对象,E作为EventArgs的)把手Button1.Click    昏暗oleDbConn作为新OleDb.OleDbConnection(ConfigurationManager.ConnectionStrings(BookMeetConnString)。ConnectionString中)
    昏暗的SqlString作为字符串=INSERT INTO活动(EVENTTITLE,EventDescription,EVENTDATE,EventCategory)值
 (@ F1,F2 @,@ F3,F4 @)
    昏暗CMD作为OleDbCommand的=新的OleDbCommand(的SqlString,oleDbConn)
    cmd.CommandType = CommandType.Text
    cmd.Parameters.AddWithValue(@ F1,tb_eventtitle.Text)
    cmd.Parameters.AddWithValue(@ F2,tb_eventdescription.Text)
    cmd.Parameters.AddWithValue(@ F3,DateTime.ParseExact(tb_eventdate.Text,DD / MM / YYYY
   CultureInfo.InvariantCulture))
    cmd.Parameters.AddWithValue(@ F4,dd_eventcategory.Text)
    oleDbConn.Open()
    cmd.ExecuteNonQuery()
    System.Threading.Thread.Sleep(2000)
    的Response.Redirect(〜/ calendar.aspx)
结束小组



解决方案

我建议你使用 DateTime.ParseExact 静态方法,尤其是这oveload:

DateTime.ParseExact(textBox.Text,DD / MM / YYYY, CultureInfo.InvariantCulture

这将解析你必须指定具体格式的文本(DD / MM / YYYY目前,情况下,重要的是毫米为分钟而不是 MM 是个月)。 CultureInfo.InvariantCulture 使用保证日期分隔将从格式字符串(第二个参数)进行检索。我注意到,如果使用目前的文化,它会覆盖传递给 ParseExact 格式字符串的某些方面。


上的CultureInfo的说明

不变的文化,是您的本地开发环境可能有不同的区域信息设置比部署环境的原因也不错。通常情况下,.NET使用在所有的的ToString 通话和隐含的格式或解析在当前文化。当强制的格式和文化不变性明确,你就不太容易出现问题,你不能在本地繁殖,但在生产中的应用存在。


上日期的说明/时间格式

通过准确的分析,该日期时间格式预期的严格的匹配输入的格式。那么你应该考虑下面的例子:


  • DD 只有两位数的日子相匹配。因此,DD / MM / YYYY将匹配2013年1月1日,但失败2013年1月1日,因为它预计位数日部分的确切人数。如果你不想前导零使用: D / M / YYYY 来代替。单字母表示数天低于 10 一位数和两位数他人。

  • MM 匹配两位数的月份,因此,所有适用于 DD ð是一样好几个月了。

  • YYYY 预计今年将在4位。如果使用两位数的年份,使用 YY 代替。


在某些ADO.NET提供的说明

作为它原来是与MS访问的情况下,正确地解析日期时间对象不足以使查询工作。目前,以下code

  cmd.Parameters.AddWithValue(...)

用于参数添加到查询。然而,该方法省略了传递信息的ADO.NET分贝提供商告诉使用什么数据库类型的参数。我看了一些论坛上的MS Access / OleDb的是不能够解决在所有情况下正确的类型。因此,我建议采用以下方法:

 暗淡作为PRM = OleDbParameter _
   新OleDbParameter(@ dateTimeParameterName,OleDbType.DateTime)
prm.Value =值'值分析System.DateTime`的`实例
                   从输入'
cmd.Parameters.Add(PRM)

以上code允许明确指定参数数据库类型,所以OLEDB驱动程序现在能够正确地传递的DateTime 对象到MS Access数据库。

I am trying to insert into a database - various details about an event. The asp.net textbox is using the Calendar Extender (so a little calendar pops up and fills the textbox with a correctly formatted date). The EventDate field in my Access database is of the type Date/Time. I need to convert the text/string to date/time format

I have tried this so far:

VB:

Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click

    Dim oleDbConn As New OleDb.OleDbConnection(ConfigurationManager.ConnectionStrings("BookMeetConnString").ConnectionString)
    Dim SqlString As String = "Insert into Events(EventTitle,EventDescription,EventDate,EventCategory) Values
   (@f1,@f2,@f3,@f4)"
    Dim cmd As OleDbCommand = New OleDbCommand(SqlString, oleDbConn)

    Dim strDate As String = tb_eventdate.Text
    Dim dtfi As New System.Globalization.DateTimeFormatInfo
    dtfi.ShortDatePattern = "dd/MM/yyyy"
    dtfi.DateSeparator = "/"
    Dim objDate As DateTime = Convert.ToDateTime(strDate, dtfi)

    cmd.CommandType = CommandType.Text
    cmd.Parameters.AddWithValue("@f1", tb_eventtitle.Text)
    cmd.Parameters.AddWithValue("@f2", tb_eventdescription.Text)
    cmd.Parameters.AddWithValue("@f3", tb_eventdate.Text)
    cmd.Parameters.AddWithValue("@f4", dd_eventcategory.Text)
    oleDbConn.Open()
    cmd.ExecuteNonQuery()
    System.Threading.Thread.Sleep("2000")
    Response.Redirect("~/calendar.aspx")
End Sub

Here is my clientside code just for reference:

 <h1>Add An Event!<ajaxToolkit:ToolkitScriptManager
 ID="ToolkitScriptManager1" 
                   runat="server">
               </ajaxToolkit:ToolkitScriptManager>
            </h1>
            <p>Title of Event:
                <asp:TextBox ID="tb_eventtitle" runat="server"></asp:TextBox>
            </p>
            <p>Event Description:
                <asp:TextBox ID="tb_eventdescription" runat="server"></asp:TextBox>
            </p>
            <p>Event Date:
                <asp:TextBox ID="tb_eventdate" runat="server"></asp:TextBox>
                <ajaxToolkit:CalendarExtender ID="tb_eventdate_CalendarExtender" runat="server" 
                    TargetControlID="tb_eventdate">
                </ajaxToolkit:CalendarExtender>
            </p>
            <p>Event Category:
                <asp:DropDownList ID="dd_eventcategory" runat="server" 
                    DataSourceID="SqlDataSource1" DataTextField="CategoryTitle" 
                    DataValueField="CategoryTitle">
                </asp:DropDownList>
            </p>
            <p>
                <asp:Button ID="Button1" runat="server" Text="Submit" />
            </p>

When I try to fill out the form, I receive this error:

My Two questions are:

  1. What is wrong with the code above, and how do I successfully use the DateTimeFormatInfo class to convert String to Date/Time?
  2. On a side note, the Calendar Extender inputs the date into the textbox in American Time format (MM/DD/YYYY), how do I change this to British (DD/MM/YYYY) format (I couldn't see an obvious property in the properties dialog to do this?)

Thanks in advance for your answers!

Adam

EDIT: Updated code below:

Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click

    Dim oleDbConn As New OleDb.OleDbConnection(ConfigurationManager.ConnectionStrings("BookMeetConnString").ConnectionString)
    Dim SqlString As String = "Insert into Events(EventTitle,EventDescription,EventDate,EventCategory) Values
 (@f1,@f2,@f3,@f4)"
    Dim cmd As OleDbCommand = New OleDbCommand(SqlString, oleDbConn)
    cmd.CommandType = CommandType.Text
    cmd.Parameters.AddWithValue("@f1", tb_eventtitle.Text)
    cmd.Parameters.AddWithValue("@f2", tb_eventdescription.Text)
    cmd.Parameters.AddWithValue("@f3", DateTime.ParseExact(tb_eventdate.Text, "dd/MM/yyyy",
   CultureInfo.InvariantCulture))
    cmd.Parameters.AddWithValue("@f4", dd_eventcategory.Text)
    oleDbConn.Open()
    cmd.ExecuteNonQuery()
    System.Threading.Thread.Sleep("2000")
    Response.Redirect("~/calendar.aspx")
End Sub

解决方案

I'd recommend you use DateTime.ParseExact static method, especially this oveload:

DateTime.ParseExact(textBox.Text, "dd/MM/yyyy",CultureInfo.InvariantCulture)

This will parse the text you have by the concrete format you specify ("dd/MM/yyyy" currently, case is important since mm is minutes as opposed to MM being months). Use of CultureInfo.InvariantCulture guarantees that date separators will be retrieved from the format string (the second parameter). I have noticed that if current culture is used, it overrides some aspects of the format string you pass to ParseExact.


A note on CultureInfo

Invariant culture is good also for the reason that your local dev environment may have different regional information setup than the deployment environment. Usually, .NET uses the current culture in all .ToString calls and implicit formatting or parsing. When forcing a format and culture invariance explicitly, you are less prone to problems you cannot reproduce locally but exist on the production application.


A note on date/time formats

With exact parsing, the datetime format is expected to strictly match the format of the input. You should then take into consideration the following examples:

  • dd matches two-digit days only. So "dd/MM/yyyy" it will match "01/01/2013", but will fail for "1/1/2013" because it expects the exact number of digits for the day part. If you do not want leading zeros use: d/M/yyyy instead. Single letter means one digit for days less than 10 and two digits for the others.
  • MM matches two-digit month, so all that applies to dd vs. d is the same for months.
  • yyyy expects the year to be in 4 digits. If you use two-digit year, use yy instead.

A note on some ADO.NET providers

As it turns out to be the case with MS Access, the correctly parsed date-time object is not sufficient to make the query work. Currently, the following code

 cmd.Parameters.AddWithValue(...)

is used to add parameters to the query. However, this approach omits passing information to the ADO.NET db provider that tells what database type to use for the parameter. I have read on some forums that MS Access/OleDb is not capable to resolve the correct type in all cases. Therefore I recommend the following approach:

Dim prm as OleDbParameter = _
   New OleDbParameter("@dateTimeParameterName", OleDbType.DateTime)
prm.Value = value  'value is an instance of `System.DateTime` parsed 
                   'from the input
cmd.Parameters.Add(prm)

The above code allows to specify the parameter database type explicitly, so the OleDb driver is now capable of correctly passing the DateTime object to the MS Access database.

这篇关于转换ASP.NET文本框控件的.text内容,日期/时间格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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