zoukankan      html  css  js  c++  java
  • What is the proper way to bind Nullable DateTime property to DateTimePicker?

    I have an object that I'm trying to bind its properties to two DateTimePicker controls.

    class Order
    {
    public DateTime OrderPlacedDate { get; }
    public Nullable<DateTime> ShippedDate { get; }
    }
    

    What is the proper way to bind Nullable DateTime Property to DateTimePicker?

    There's not really a right way since the DateTimePicker does not have good support for null values. You have a couple of options:

    1. You can use a ReadOnly TextBox and a MonthCalendar rather than a DateTimePicker. You'd bind to the TextBox and use the MonthCalendar to set the date in the TextBox.

    2. You can use DateTimePicker's null support which is a little clumsy from a UI perspective. This also requires you to write some glue code that maps the DateTimePicker's null representation to a null on your Nullable<DateTime> property. You can do this as follows:

    Customer _customer; // Has a Nullable<DateTime> property called "HireDate"
    private void Form1_Load(object sender, EventArgs e)
    {
    // Create Customer
    _customer = new Customer("555", "John Doe", 1000, DateTime.Now);
    // Bind
    Binding binding = new Binding("Value", _customer, "HireDate", true);
    this.dateTimePicker1.DataBindings.Add(binding);
    // BindingComplete
    binding.Format += new ConvertEventHandler(Binding_Format);
    binding.Parse += new ConvertEventHandler(Binding_Parse);
    }
    void Binding_Parse(object sender, ConvertEventArgs e)
    {
    // Need to make the Control show NULL
    Binding binding = sender as Binding;
    if (null != binding)
    {
    DateTimePicker dtp = (binding.Control as DateTimePicker);
    if ((null != dtp) && (dtp.Checked))
    e.Value = new Nullable<DateTime>();
    }
    }
    void Binding_Format(object sender, ConvertEventArgs e)
    {
    INullableValue inv = (e.Value as INullableValue);
    if ((null != inv) && (!inv.HasValue))
    {
    // Need to make the Control show NULL
    Binding binding = sender as Binding;
    if (null != binding)
    {
    DateTimePicker dtp = (binding.Control as DateTimePicker);
    if (null != dtp)
    {
    dtp.ShowCheckBox = true;
    dtp.Checked = false;
    e.Value = dtp.Value;
    }
    }
    }
    }
    
    ---------------------------------------------------------------------
    每个人都是一座山.世上最难攀越的山,其实是自己.往上走,即便一小步,也有新高度
    .

    --做最好的自己,我能!!!

  • 相关阅读:
    Hdu 5256 系列转换
    SQL在declare声明变量
    煤火车问题
    百度音乐接口-——这可以基于在线音乐播放器来完成
    Android DrawerLayout 抽屉
    NETSH WINSOCK RESET这个命令的意义和效果?
    SSH三作品的框架和流程
    Solr入门指南
    客房收费制度的具体配置
    基本调试命令
  • 原文地址:https://www.cnblogs.com/tonyepaper/p/1203659.html
Copyright © 2011-2022 走看看