【问题标题】:make relative string as per selected options from checkboxlist in asp.net根据asp.net中复选框列表中的选定选项制作相对字符串
【发布时间】:2016-08-02 05:49:39
【问题描述】:

我正在制作实践管理系统,我需要在其中添加诊所或医院可以在其诊所或医院添加访问医生的功能。下面是mu当前界面。

此处诊所或医院选择日期并输入时间,以便所有选定的日期都获得该时间。现在我想创建一个字符串,其中的值可以像这样存储

周一、周三、周五
上午 10 点至下午 2 点

我可以使用此代码执行上述字符串

string selectedDays = string.Empty;
foreach (ListItem chk in daySelect.Items) {
    if (chk.Selected == true) {
        selectedDays += chk.Text + ",";
    }
}

string vistingDays = string.Empty;
vistingDays = selectedDays + "<br />" + frmTime.SelectedValue.ToString + "-" + ToTime.SelectedValue.ToString;

如果连续选择日期,即周一周二周三周四,那么它应该得到这样的字符串值。这里唯一的区别是,如果他们选择连续的 2 天以上,那么它会以破折号而不是逗号作为分隔符。

周一至周四
上午 10 点至下午 2 点

我需要帮助来使用我的代码执行上述操作。如果我的帖子很复杂,请原谅我在这里发布的方式,但我真的需要帮助。

【问题讨论】:

    标签: c# asp.net


    【解决方案1】:

    不是最易读的解决方案,但它有效,如果有人使用 LINQ 或更少代码有某种聪明的解决方案,我很乐意看到它,但如果没有其他人回答,欢迎您使用我的代码,只需正确测试它所有可能的场景:

    protected void btnSave_Click(object sender, EventArgs e)
    {
        string selectedDays = String.Empty;
        int j = 0;
    
        var items = new Dictionary<int,string>();
    
        for (int i = 0; i < daySelect.Items.Count; i++)
            items.Add(i, daySelect.Items[i].Selected ? daySelect.Items[i].Text : "");
    
        for (int i = 0; i < items.Count; i++ )
        {
            string current = items.ElementAt(i).Value;
    
            if(String.IsNullOrEmpty(selectedDays))
            {
                j = items.ElementAt(i).Key;
                selectedDays = current;
                continue;
            }
            else if(current != "")
            {
                if((j + 1) == i)
                {
                    int lastComma = selectedDays.LastIndexOf(',');
                    int lastDash = selectedDays.LastIndexOf('-');
    
                    if ((selectedDays.Contains('-') && !selectedDays.Contains(',')) || lastDash > lastComma)
                    {
                        string day = selectedDays.Substring(selectedDays.LastIndexOf('-') + 1, 3);
                        selectedDays = selectedDays.Replace(day, current);
                    }
                    else
                        selectedDays += ("-" + current);
    
                    j = items.ElementAt(i).Key;
                }
                else
                {
                    selectedDays += "," + current;
                    j = items.ElementAt(i).Key;
                }
            }
        }
    
        string vistingDays = selectedDays + "<br />" + frmTime.SelectedValue.ToString() + "-" + ToTime.SelectedValue.ToString();
    }
    

    【讨论】:

      猜你喜欢
      • 2015-08-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多