Visual Studio中DateTimePicker赋值遇BC30068及类型转换问题求助
解决DateTimePicker赋值分拆日/月/年的问题
这个问题我之前也碰到过,核心原因是DateTime是值类型——DateTimePicker的Value属性返回的是DateTime结构体的副本,你直接修改它的Day/Month/Year属性,本质上只是改了这个临时副本,根本影响不到控件的实际值,所以编译器会抛出BC30068错误。
要解决这个问题,正确的思路是:用从数据库读取到的日、月、年值重新构造一个完整的DateTime对象,再把这个对象整体赋值给DateTimePicker的Value属性。同时还要处理好类型转换的问题,避免“整数无法转换为整数”的报错(大概率是因为数据库读取的是Object类型,没有正确转成Integer)。
具体实现代码(VB.NET)
' 假设row是你的DataRow对象,存储了从数据库读取的记录 Dim dag As Integer Dim maand As Integer Dim jaar As Integer ' 先处理数据库值的安全转换,避免空值或格式错误导致异常 If Not IsDBNull(row("geboortedag")) AndAlso Not IsDBNull(row("geboortemaand")) AndAlso Not IsDBNull(row("geboortejaar")) Then ' 用Integer.TryParse做安全转换,防止非整数内容导致崩溃 If Integer.TryParse(row("geboortedag").ToString(), dag) AndAlso _ Integer.TryParse(row("geboortemaand").ToString(), maand) AndAlso _ Integer.TryParse(row("geboortejaar").ToString(), jaar) Then ' 构造完整的DateTime对象 Dim geboorteDatum As New DateTime(jaar, maand, dag) ' 整体赋值给DateTimePicker的Value属性 dtp_geboortedatum.Value = geboorteDatum Else ' 处理转换失败的情况,比如设置默认日期或提示用户 dtp_geboortedatum.Value = DateTime.Today MsgBox("Geboortedatum gegevens zijn ongeldig!") End If Else ' 处理数据库字段为空的情况 dtp_geboortedatum.Value = DateTime.Today MsgBox("Geboortedatum ontbreekt in de database!") End If
关键细节说明
- 不能直接修改Value的属性:DateTime是值类型,每次访问
dtp_geboortedatum.Value都会返回一个新的副本,修改副本的属性对原控件毫无意义,必须构造新对象整体赋值。 - 安全类型转换:数据库读取的字段默认是Object类型,直接用
CInt()转换如果遇到空值或非整数会抛出异常,用Integer.TryParse可以优雅处理转换失败的场景。 - 空值处理:如果数据库允许日/月/年字段为NULL,一定要先判断
IsDBNull,避免空引用异常。
内容的提问来源于stack exchange,提问作者Gaius Vulcanus Duodecimus
相关产品推荐
相关产品推荐

