这还是一个菜鸟,所以请耐心等待。 我的问题的简短版本是我有一个月份日历,其中包含一系列日期并将它们添加到标签
Dim iStart as DateTime = MonthCalendar1.SelectionRange.Start.ToShortDatestring
Dim iEnd as DateTime = MonthCalendar1.SelectionRange.End.ToShortDatestring
Dim iCount as DateTime = iStart
While iCount <= iEnd
iCount = iCount.AddDays(1)
Lable1.Text = Label1.Text & iCount & vbNewLine
End With
现在完美无缺。但这是我想要添加到数据库的单个记录的一部分。所以考虑做一个For Each循环,但得到上面提到的错误 - 类型的值&#39; Char&#39;无法转换为&#39;日期&#39; 这是代码的开头
For Each iCount in label1.text 'This is where the error comes up
请帮忙
答案 0 :(得分:1)
由于你已经使用了一个常见的分隔符“vbNewLine”,尝试使用Split
来检索它们,尽管你最好首先使用像Plutonix状态这样的List(of T)。 / p>
这是一个使用我以前测试的控制台应用程序的示例,因此UI元素不存在,并被等效变量替换。
使用Split
Sub Main()
Dim iStart As DateTime = New DateTime(2014, 1, 1)
Dim iEnd As DateTime = New DateTime(2014, 1, 15)
Dim iCount As DateTime = iStart
Dim LabelText As String
Dim temp()
While iCount <= iEnd
iCount = iCount.AddDays(1)
LabelText = LabelText & iCount & vbNewLine
End While
temp = LabelText.Split(vbNewLine) 'This seperates the single string back to individual entrys
For Each s As String In temp
Console.WriteLine(DateTime.Parse(s)) 'Add to DataBase here.
Next
End Sub
使用List(of DateTime)
无需重新转换即可轻松实现。
Sub Main()
Dim iStart As DateTime = New DateTime(2014, 1, 1)
Dim iEnd As DateTime = New DateTime(2014, 1, 15)
Dim iCount As DateTime = iStart
Dim LabelText As String
Dim tempDate As List(Of DateTime) = New List(Of DateTime)
While iCount <= iEnd
iCount = iCount.AddDays(1)
tempDate.Add(iCount) 'Just add it here no conversion necessary
LabelText = LabelText & iCount & vbNewLine
End While
For Each d As Date In tempDate
Console.WriteLine(d) 'Add to Database here using Console.WriteLine as example
Next
End Sub
答案 1 :(得分:1)
您可以将其转换为一行(长)代码:
Dim Days() As DateTime = Enumerable.Range(0, (MonthCalendar1.SelectionRange.End.Date - MonthCalendar1.SelectionRange.Start.Date).Days).Select(Function(i) MonthCalendar1.SelectionRange.Start.AddDays(i)).ToArray()
为了便于阅读,将其分解一下:
Dim start As DateTime = MonthCalendar1.SelectionRange.Start.Date
Dim stop As DateTime = MonthCalendar1.SelectionRange.End.Date
Dim Days() As DateTime = Enumerable.Range(0, (stop - start).Days).
Select(Function(i) start.AddDays(i)).ToArray()
然后从您已有的Days()
数组构建标签字符串,而不是先构建标签并稍后重建数组。
Lable1.Text = String.Join(vbCrLf, Days)