【问题标题】:How to set a DatePicker's value dynamically?如何动态设置 DatePicker 的值?
【发布时间】:2020-03-09 16:51:41
【问题描述】:

我的表单中有一个对象 datePicker 来显示出生日期。我从我的数据库中读取了出生日期(日期是格式为“yyyyMMdd”的字符串)我尝试使用以下代码设置在 datePicker 中读取的日期,但出现异常。我做错了什么?!?

birth.Value= new DateTime(extractDate(r["H1DTN0"].ToString())); 


public long extractDate(String s)
    {
        String y = "";
        String m = "";
        String d = "";
        if(s.Length==8)
        {
            int index = 0;
            foreach(char c in s)
            {
                if (index <= 3) y += c;
                else if (index >3 && index <= 5) m += c;
                else if (index >5) d += c;
                index++;
            }
            String data = y + m + d;
            long l = 0;
            long.TryParse(data,out l);

            return l;
        }
        else
        {

            return 0;


        }



    }

【问题讨论】:

  • 这是 WinForms 吗? WPF?还有什么?
  • 日期没有格式,所以摒弃这个概念。将 DateTimePicker 的 .Value 属性设置为有效的 DateTime 值和利润!
  • 什么异常?
  • @Zer0 它表示 minValue 和 MaxValue 之间不包含值,而是它
  • 您对DateTime 的概念非常扭曲和错误。推荐阅读DateTime Documentation

标签: c# datepicker


【解决方案1】:

我找到了解决方案:

DateTime dtbIRTH = DateTime.ParseExact(extractDate(r["H1DTN0"].ToString()), "yyyyMMdd", CultureInfo.InvariantCulture);
                    birth.Value= dtbIRTH;

使用 DateTime.ParseExact 并指定日期格式,它可以完美运行。

【讨论】:

    猜你喜欢
    • 2012-07-15
    • 2020-11-08
    • 1970-01-01
    • 2011-09-17
    • 2017-02-22
    • 2023-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多