自动编号生成方法
一、按月生成编号
假定有个表,需要按月自动生成编号,四位年,两位月,最后三位是顺序号,如下图所示:
要自动生成上述编号,只需将表事件DataColChanged的代码设置为:
If
e.DataCol.Name = "日期" Then
If e.DataRow.IsNull("日期") Then
e.DataRow("编号") = Nothing
Else
Dim d As Date = e.DataRow("日期")
Dim y As Integer = d.Year
Dim m As Integer = d.Month
Dim Days As Integer = Date.DaysInMonth(y,m)
Dim fd As Date = New Date(y,m,1) '获得该月的第一天
Dim ld As Date = New Date(y,m,Days) '获得该月的最后一天
Dim bh As String = Format(d,"yyyyMM") '生成编号的前6位,4位年,2位月.
If e.DataRow("编号").StartsWith(bh) = False '如果编号的前6位不符
Dim max As String
Dim idx As Integer
max = e.DataTable.Compute("Max(编号)","日期 >= #" & fd & "# And 日期 <= #" & ld & "#") '取得该月的最大编号
If max > "" Then '如果存在最大编号
idx = CInt(max.Substring(7,3)) + 1 '获得最大编号的后三位顺序号,并加1
Else
idx = 1 '否则顺序号等于1
End If
e.DataRow("编号") = bh & "-" & Format(idx,"000")
End If
End If
End If
二、按日生成编号
假定有个表,需要按天自动生成编号,四位年,两位月,两位日,最后三位是顺序号,如下图所示:
要自动生成上述编号,代码更加简单:
If
e.DataCol.Name = "日期" Then
If e.DataRow.IsNull("日期") Then
e.DataRow("编号") = Nothing
Else
Dim bh As String = Format(e.DataRow("日期"),"yyyyMMdd") '取得编号的8位前缀
If e.DataRow("编号").StartsWith(bh) = False '如果编号的前8位不符
Dim max As String
Dim idx As Integer
max = e.DataTable.Compute("Max(编号)","日期 = #" & e.DataRow("日期") & "#") '取得该天的最大编号
If max > "" Then '如果存在最大编号
idx = CInt(max.Substring(9,3)) + 1 '获得最大编号的后三位顺序号,并加1
Else
idx = 1 '否则顺序号等于1
End If
e.DataRow("编号") = bh & "-" & Format(idx,"000")
End If
End If
End If