在 vb.net 的 datagridview 中生成星期几

Generate days of the week in datagridview in vb.net

我试图根据组合框的选定时间段在我的 datagridview header 中获取星期几

到目前为止,我已经取得了以下成绩来确定星期几,但我注意到我总是得到 31。

2 月我们只有 28 天的时间,下面的部分代码我失败了

    Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
    Dim dias_de_la_semana As New ArrayList From {"LUN", "MAR", "MIE", "JUE", "VIEW", "SAB", "DOM"}
    Dim MiFecha As Date = Now ' o toda otra fecha
    Dim Limite As Integer = 31  ' Puestas el valor que quieres
    For i As Integer = 1 To Limite Step 7
        For j = 0 To 7
            If i + j <= Limite Then
                dgvdias.Columns.Add(0, dias_de_la_semana(MiFecha.DayOfWeek) & "-" & i + j)
            Else
                i = Limite
                Exit For
            End If
            MiFecha = MiFecha.AddDays(1)
        Next
    Next
End Sub

尝试更改线路

 Dim Limite As Integer = 31

进入

Dim Limite As Integer = System.DateTime.DaysInMonth(MiFecha.Year, MiFecha.Month)

闰年的二月可以有 29 天。因此,您必须计算当前年份才能准确。查看 here 了解如何轻松检索当月的天数。

此外,不建议手动填充 DGV,我建议改用数据表,并将其用作 DGV 的数据源。可能您会想要做更多事情并使用用户输入填充网格以将数据保存到数据库。

一个简单的例子:

dim current_year as integer = 2020
dim current_month as integer = 2
Dim days_in_month As Integer = System.DateTime.DaysInMonth(current_year, current_month)

System.Console.WriteLine("Days in month: " & days_in_month)

' start at 1st day of current month
dim d as new DateTime(current_year, current_month, 1)
' offset -1 day for the loop
d = d.AddDays(-1)

for i as integer = 1 to days_in_month
    ' date1 = new DateTime(2008, 5, 1, 8, 30, 52);
    d = d.AddDays(1)
    System.Console.WriteLine("Day: " & i & " - date: " & d.ToString("dddd, MMMM dd"))
next

输出:

Days in month: 29
Day: 1 - date: Saturday, February 01
Day: 2 - date: Sunday, February 02
Day: 3 - date: Monday, February 03
Day: 4 - date: Tuesday, February 04
Day: 5 - date: Wednesday, February 05
Day: 6 - date: Thursday, February 06
Day: 7 - date: Friday, February 07
Day: 8 - date: Saturday, February 08
Day: 9 - date: Sunday, February 09
Day: 10 - date: Monday, February 10
Day: 11 - date: Tuesday, February 11
Day: 12 - date: Wednesday, February 12
Day: 13 - date: Thursday, February 13
Day: 14 - date: Friday, February 14
Day: 15 - date: Saturday, February 15
Day: 16 - date: Sunday, February 16
Day: 17 - date: Monday, February 17
Day: 18 - date: Tuesday, February 18
Day: 19 - date: Wednesday, February 19
Day: 20 - date: Thursday, February 20
Day: 21 - date: Friday, February 21
Day: 22 - date: Saturday, February 22
Day: 23 - date: Sunday, February 23
Day: 24 - date: Monday, February 24
Day: 25 - date: Tuesday, February 25
Day: 26 - date: Wednesday, February 26
Day: 27 - date: Thursday, February 27
Day: 28 - date: Friday, February 28
Day: 29 - date: Saturday, February 29

您可以根据需要调整日期格式。