VB.NET中DateTimePicker.Value无法接收传入日期字符串的问题
我在一个窗体中列出了一系列服务及其对应的日期,每个服务旁配有复选框,复选框旁边是DateTimePicker控件:若复选框被勾选,DateTimePicker将显示并设置为该服务的合同结束日期;若未勾选,则隐藏该控件(Visible=False)。
我通过以下代码从MySQL读取数据并存储到DataTable中:
Dim adapter As MySqlDataAdapter Dim productresultstable As DataTable cn.ConnectionString = main.myconnectionstr Dim commandtext As String commandtext = "Select * from products where link_id = '" & customerid & "'" adapter = New MySqlDataAdapter(commandtext, cn) productresultstable = New DataTable adapter.Fill(productresultstable)
随后遍历数据,设置对应的复选框和DateTimePicker:
p1.Checked = productresultstable.Rows(0)("p1").ToString() If p1.Checked = True Then p1date.Visible = True p1date.Value = Date.Parse(productresultstable.Rows(0)("1_ce").ToString) End If
复选框功能正常,能正确勾选,但所有DateTimePicker都显示当天日期。我确认productresultstable.Rows(0)("1_ce").ToString可以正确获取到日期(MySQL中1_ce列为Date类型),通过MessageBox显示的值为"19/04/2018 00:00:00",但无论尝试何种方法,都无法将该值设置到对应的DateTimePicker的Value属性中。恳请各位指点解决方向,感谢帮助!
我之前也碰到过类似的DateTimePicker赋值问题,给你几个实用的排查和解决方向:
不要用
Date.Parse,改用指定格式的Date.TryParseExactDate.Parse会依赖系统的区域日期格式设置,如果你的系统默认格式和MySQL返回的dd/MM/yyyy HH:mm:ss不匹配,就会解析失败,默认返回当前日期。你可以明确指定格式来确保解析准确:Dim targetDate As Date ' 匹配你拿到的日期字符串格式,这里是dd/MM/yyyy加时分秒 If Date.TryParseExact(productresultstable.Rows(0)("1_ce").ToString, _ "dd/MM/yyyy HH:mm:ss", _ Globalization.CultureInfo.InvariantCulture, _ Globalization.DateTimeStyles.None, _ targetDate) Then p1date.Value = targetDate End If直接读取DateTime类型,跳过字符串转换
MySQL的Date类型在DataTable中本身就可以直接转为DateTime对象,没必要先转成字符串再解析,这样能彻底避免格式问题:' 直接类型转换 p1date.Value = CType(productresultstable.Rows(0)("1_ce"), DateTime) ' 或者更安全的Convert方法 p1date.Value = Convert.ToDateTime(productresultstable.Rows(0)("1_ce"))检查DateTimePicker的显示格式设置
有时候不是赋值失败,而是控件的显示格式不对导致看起来像当前日期。你可以把DateTimePicker的Format属性改成Custom,然后设置CustomFormat为dd/MM/yyyy,看看是不是显示的问题。排查是否有其他代码覆盖了Value值
确认在这段赋值代码之后,有没有其他地方修改了p1date.Value——比如窗体的其他加载事件、控件的ValueChanged事件里的代码,不小心把值改回了当前日期。
内容的提问来源于stack exchange,提问作者John

