自动计算datagridview

时间:2016-05-06 07:55:44

标签: vb.net datagridview

如何在datagridview中自动计算列?

当您将公式设置为列时,像microsoft excel中的东西。

我有一个约会专栏和一个任期专栏。任期列应使用DateHired - DateToday公式自动计算。

请帮忙。谢谢。

2 个答案:

答案 0 :(得分:0)

您可以将GridView中的偶数"CellEndEdit"称为:

   Private Sub Form2_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        DataGridView1.Columns.Add("DateHired", "DateHired")
        DataGridView1.Columns.Add("tenure", "tenure")

    End Sub
Private Sub DataGridView1_CellEndEdit(sender As Object, e As DataGridViewCellEventArgs) Handles DataGridView1.CellEndEdit
        Try
            Dim order As DataGridView = DirectCast(sender, DataGridView)

            If IsDate(order("DateHired", e.RowIndex).Value) Then
                'Dim dt As Date = order("DateHired", e.RowIndex).Value
                Dim dt1 As Date = order("DateHired", e.RowIndex).Value
                Dim dt2 As Date = Date.Parse(DateTime.Now)
                ' order("tenure", e.RowIndex).Value = DateDiff(DateInterval.Year, dt, Date.Now)
                order("tenure", e.RowIndex).Value = Math.Abs(CInt(dt1.Subtract(dt2).TotalDays / 30))
            End If

        Catch ex As Exception

        End Try
    End Sub
    Private Sub DateTimePicker1_ValueChanged(sender As Object, e As EventArgs) Handles DateTimePicker1.ValueChanged

        Dim dt1 As Date = Date.Parse(DateTimePicker1.Text)
        Dim dt2 As Date = Date.Parse(DateTime.Now)
        txtTenure.Text = Math.Abs(CInt(dt1.Subtract(dt2).TotalDays / 30))
    End Sub

答案 1 :(得分:0)

您可以使用以下语句计算两个日期之间的年/月/日以及更多日期。

LblDateDiff.Text = DateDiff(DateInterval.Year, DateTimePicker1.Value, DateTimePicker2.Value)

您可以通过任何有效日期代替DateTimePicker1.value& DateTimePicker2.value

您可以使用其他选项代替DateInterval.Year,如下所示。

  • DAYOFYEAR
  • 小时
  • 分钟
  • 第二
  • 平日
  • WEEKOFYEAR

要在DataGridView中使用上述功能,您可以使用以下代码。

Dim ds As New DataSet
qry = "select * from TblDate"
Dim da As New SqlDataAdapter(qry, con)
da.Fill(ds)
If ds.Tables(0).Rows.Count > 0 Then
DataGridView1.DataSource = ds.Tables(0)
DataGridView1.Columns.Add("Days", "Days")
For i = 0 To DataGridView1.Rows.Count - 1
    With DataGridView1.Rows(i)
        .Cells(1).Value = DateDiff(DateInterval.Day, .Cells(0).Value, Today.Date)
    End With
Next

在上面的示例中,您将获得图片中提到的输出,当前日期为2016年5月7日enter image description here

enter image description here