如何设置组合框值

时间:2011-03-10 08:14:46

标签: c# winforms

昨天我问了这个问题:Get current time and set a value in a combobox

现在我有另一个我必须处理的问题。在昨天我问的问题中,我的组合框中有三个区域:

06:00 - 14:00组合框将获得值 TimeZone 1

14:01 - 22:00组合框将获得值 TimeZone 2

22:01 - 05:59组合框将获得值 TimeZone 3

我还有一个datTimePicker,用户可以选择日期。假设用户选择:2011-02-02并在时区组合框中选择TimeZone 2.如果发生这种情况,我想创建一个只搜索时间的方法。在14:01 - 22:00之间(TimeZone 2)。如果用户选择TimeZone 3,它只会搜索22:01 - 05:59之间的时间。

有什么想法吗?

2 个答案:

答案 0 :(得分:1)

您可以创建一个包含Type,from和to time的Period holder类。这可以插入像IList这样的集合中,可以用作组合框的数据源。像这样的例子:

    [Test]
    public void CompositeDictionary()
    {

        //Create a dictionary of periods
        IList<PeriodHolder> periodHolders = new List<PeriodHolder>();
        periodHolders.Add(new PeriodHolder("Type1", "06:00", "14:00"));
        periodHolders.Add(new PeriodHolder("Type2", "14:01", "22:00"));
        periodHolders.Add(new PeriodHolder("Type3", "22:01", "05:59"));

        //Create the test combobox in a test form
        Form testForm = new Form();
        ComboBox testComoBox = new ComboBox();
        testForm.Controls.Add(testComoBox);

        testComoBox.DataSource = periodHolders;
        testComoBox.ValueMember = "PeriodName"; //The name of the Name property in PeriodHolder
        testComoBox.DisplayMember = "PeriodString"; //The name of the PeriodString property in PeriodHolder
        testComoBox.SelectedIndex = 1;


        string selectedType = testComoBox.ValueMember[testComoBox.SelectedIndex].ToString(); //Get the type so you can lookup in dictionary


        foreach (PeriodHolder periodHolder in periodHolders)
        {
            if (periodHolder.PeriodName == selectedType)
            {
                //Use period holder for whatever you need

                string fromTime = periodHolder.TimeFrom; //Extract fromTime from periodholder
                string toTime = periodHolder.TimeTo;     //Extract toTime from periodholder

                Console.WriteLine(periodHolder.PeriodString);

                break; //you've found it -- Don't look anymore
            }
        }



    }

    public class PeriodHolder
    {
        public PeriodHolder(string name, string from, string to)
        {
            PeriodName= name;
            TimeFrom =from;
            TimeTo = to;
        }
        public string PeriodName { get; set; }
        public string TimeFrom { get; set; }
        public string TimeTo { get; set; }

        public string PeriodString
        {
            get
            {
                return TimeFrom + " - " + TimeFrom;
            }
        }
    }

答案 1 :(得分:0)

创建一个包含3个输入参数的方法,如GetTime(DateTimePickerValue,TimeZone,SearchedTimeDate)和返回值bool。

检查方法TimeSpan以计算时间和日期。