【问题标题】:problem with selecting date from dropdownlist从下拉列表中选择日期的问题
【发布时间】:2009-07-16 12:41:45
【问题描述】:

我正在从下拉列表中选择日期。但我收到此异常“SqlDateTime 溢出。必须在 1/1/1753 12:00:00 AM 和 12/31/9999 11:59:59 PM 之间。” 这是我的代码:

DateTime dateofjoining = new DateTime(DropDownListDay.SelectedIndex,
                                      DropDownListMonth.SelectedIndex,
                                      DropDownListYear.SelectedIndex);

在后端加入日期类型为日期时间。请修改我上面的代码。

谢谢, 苏米特

【问题讨论】:

  • 请将您的代码放入代码块中
  • 在调试这个时,你是否在“dateofjoining”被发送到数据库之前读取了它的值?我敢打赌,这不是您认为自己选择的。

标签: c# sql-server date


【解决方案1】:

您需要提取所选索引处的值并将它们转换为整数,然后再将它们传递给 DateTime 构造函数。此外,您的字段顺序在构造函数中是倒序的。

int day = int.Parse( DropDownListDay.SelectedValue );
int month = int.Parse( DropDownListMonth.SelectedValue );
int year = int.Parse( DropDownListYear.SelectedValue );

DateTime dateofjoining = new DateTime( year, month, day );

我认为,如果索引与日/月/年值正确对齐,则可以使用这些索引。请记住,索引是从零开始的。不过,我会使用选定的值。这就是他们的目的。

【讨论】:

  • 我写了这段代码,这也不起作用: DateTime dateofjoining = new DateTime(int.Parse(DropDownListDay.SelectedItem.ToString()), int.Parse(DropDownListMonth.SelectedItem.ToString()) , int.Parse(DropDownListYear.SelectedItem.ToString()))
  • 我不知道 SelectedItem 上的 ToString 方法是做什么的,但我怀疑它是否符合您的要求。如果您无法直接访问 SelectedValue(我不确定您为什么无法访问),您可以使用 SelectedItem.Value。
  • 不要忽略构造函数中值的顺序颠倒的事实。它必须是“年月日”,而不是“日月年”。
  • 嗨,tvanfosson 先生,您的代码运行良好。但是如果是月份下拉列表,我给出的是 1 月到 12 月而不是 1 到 12 日。那我该怎么做呢?它仅适用于 int 但不适用于字符串,如 1 月至 12 月。
  • DropDownList 中的每个 ListItem 都有两个属性:Text 和 Value。将 Text 设置为月份名称,但将值设置为整数值(作为字符串)。您没有显示创建下拉列表的代码,但如果您使用采用 ListItem 的 Item.Add() 方法,您应该能够执行 ddl.Items.Add( new ListItem( "January", 1 ) )
【解决方案2】:

我认为你应该使用 .SelectedValue 而不是 .SelectedIndex

【讨论】:

    【解决方案3】:

    尝试使用 SelectedValue 或 SelectedText 而不是 SelectedIndex。 SelectedIndex 只是项目在列表中的位置,而不是显示给用户的值。

    【讨论】:

    • 在 SQLServer 2000 中选择的文本属性不可用。
    • 尝试将上面的代码修改为:DateTime dateofjoining = new DateTime(DropDownListDay.SelectedValue, DropDownListMonth.SelectedValue, DropDownListYear.SelectedValue); .你也可以试试: DateTime dateofjoining = new DateTime(DropDownListDay.SelectedText, DropDownListMonth.SelectedText, DropDownListYear.SelectedText);
    猜你喜欢
    • 1970-01-01
    • 2015-10-13
    • 1970-01-01
    • 1970-01-01
    • 2013-06-20
    • 2023-02-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多