zoukankan      html  css  js  c++  java
  • 在ToolStrip中加入具有更好体验性的DateTimePicker

     一、 需求的产生
          很多时候,需要根据年月或日期来检索数据。在我的数据库中,如果只需要以月为单位,我一般按照200801这样的格式(yyyyMM)保存为int类型。在做数据检索时,是根据工具栏中的两个ToolStripComboBox(一个年,一个月)选择的数据合并成一个年月来检索数据,但是用户反映不够方便和直观,希望能够使用日期控件进行选择。效果如图:


    如果不使用工具栏很好做,而使用工具栏又没有现成的日期工具栏控件,好在微软实现了一个ToolStripControlHost类,提供了将其他控件加入ToolStrip的能力。

    二、 如何将DateTimePicker加入ToolStrip

          由于DateTimePicker继承自Control,可以作为ToolStripControlHost的构造函数的参数构造一个ToolStripControlHost实例, 然后将这个实例直接作为ToolStrip的Item插入到ToolStrip的Items集合中,即可使用。     

     this.mainToolStrip.Items.Insert(1,new ToolStripControlHost(new DateTimePicker()));

        如果不考虑控件在工具栏中的位置,可以使用Items.Add(ToolStripItem value)方法,使用Items.Insert(int index,ToolStripItem value)方法可以指定控件在工具栏中的位置。

    三、 如何设置显示格式

         DateTimePicker默认显示格式与用户要求的一般情况下不相同,需要在程序中进行设置。    

     DateTimePicker dtp = new DateTimePicker();
     dtp.Format = DateTimePickerFormat.Custom;//自定义格式
     dtp.CustomFormat = "yyyyMM";//自定义格式
     dtp.Width = 100;
     this.mainToolStrip.Items.Insert(1,new ToolStripControlHost(dtp));

    四、如何使用

         工具栏中已经加入了DateTimePicker,但是怎么使用的,这样动态加入工具栏的控件不能直接使用,我们可以按照下面的方式使用:

     int yyyyMM = Convert.ToInt32(mainToolStrip.Items[1].Text);

    五、参考文章

    1.http://www.cnblogs.com/kevinShan/archive/2007/02/01/636849.html
    2.http://msdn2.microsoft.com/zh-cn/library/5daaw6hf.aspx

  • 相关阅读:
    创建子类
    SQL优化之一则MySQL中的DELETE、UPDATE 子查询的锁机制失效案例
    linux下报错:error while loading shared libraries
    linux下报错:error while loading shared libraries
    iterm2终端manpage高亮显示
    iterm2终端manpage高亮显示
    iterm2终端manpage高亮显示
    iterm2终端manpage高亮显示
    rabbitmq文章源
    rabbitmq文章源
  • 原文地址:https://www.cnblogs.com/lgx5/p/9429634.html
Copyright © 2011-2022 走看看