如何在datagridview中自动计算列?
当您将公式设置为列时,像microsoft excel中的东西。
我有一个约会专栏和一个任期专栏。任期列应使用DateHired
- DateToday
公式自动计算。
请帮忙。谢谢。
答案 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,如下所示。
要在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