You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在C# WinForm的MonthCalendar控件中将SQL Server数据库日期加粗显示

C# WinForm MonthCalendar 加粗指定日期实现方案

1. 波兰语日期解析(仅数据库存字符串格式时需要)

你的示例日期为波兰语格式,需要使用波兰语区域配置解析为DateTime对象:

using System.Globalization;

// 初始化波兰语文化配置
CultureInfo plCulture = new CultureInfo("pl-PL");
string sampleDateStr = "czwartek, 10 listopada 2022";
DateTime parsedDate;

// 按波兰语日期格式解析,格式字符串对应:星期全名、日期、月份全名、4位年份
if (DateTime.TryParseExact(sampleDateStr, "dddd, d MMMM yyyy", plCulture, DateTimeStyles.None, out parsedDate))
{
    // 解析成功,parsedDate即为标准日期对象
}

如果你的terminr表的日期字段本身是datetime/date类型,可跳过这一步,直接从数据库读取为DateTime对象即可。

2. 从SQL Server读取terminr表的日期数据

使用ADO.NET查询表数据,收集所有需要加粗的日期:

using System.Data.SqlClient;
using System.Collections.Generic;

List<DateTime> needBoldDates = new List<DateTime>();
// 替换为你自己的数据库连接字符串
string connString = "Server=你的服务器地址;Database=你的库名;User Id=账号;Password=密码;";
// 替换为你表中存储日期的字段名
string querySql = "SELECT 日期字段名 FROM terminr";

using (SqlConnection conn = new SqlConnection(connString))
{
    conn.Open();
    using (SqlCommand cmd = new SqlCommand(querySql, conn))
    {
        using (SqlDataReader reader = cmd.ExecuteReader())
        {
            CultureInfo plCulture = new CultureInfo("pl-PL");
            while (reader.Read())
            {
                DateTime currentDate;
                // 字段为datetime/date类型时直接取值
                if (reader["日期字段名"] is DateTime dbDate)
                {
                    currentDate = dbDate.Date;
                }
                // 字段为字符串类型时走解析逻辑
                else
                {
                    string dateStr = reader["日期字段名"].ToString();
                    if (!DateTime.TryParseExact(dateStr, "dddd, d MMMM yyyy", plCulture, DateTimeStyles.None, out currentDate))
                    {
                        // 解析失败可自行添加处理逻辑,比如跳过、记录日志
                        continue;
                    }
                    currentDate = currentDate.Date;
                }
                needBoldDates.Add(currentDate);
            }
        }
    }
}

3. 给MonthCalendar控件设置加粗日期

MonthCalendar控件原生支持BoldDates属性,直接赋值即可生效:

// 去重后转为数组赋值给控件属性
monthCalendar1.BoldedDates = needBoldDates.Distinct().ToArray();
// 强制刷新控件让加粗效果立即生效
monthCalendar1.UpdateBoldedDates();

注意事项

  • 所有日期统一取.Date属性忽略时间部分,避免同一天因时间不同无法识别为同一日期的问题
  • 如果需要动态切换月份时更新加粗日期,可监听控件的DateChanged事件,重新查询对应月份的日期更新BoldDates即可
  • 如果要清空所有加粗日期,直接赋值monthCalendar1.BoldedDates = new DateTime[0];即可

内容的提问来源于stack exchange,提问作者km96

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 15:24:03