Private Sub IssueDGV_CellMouseClick(sender As Object, e As DataGridViewCellMouseEventArgs) Handles IssueDGV.CellMouseClick
Dim row As DataGridViewRow = IssueDGV.Rows(e.RowIndex)
Bidlbl.Text = row.Cells(2).Value.ToString
Booktitlelbl.Text = row.Cells(3).Value.ToString
DateTimePicker1.Value = row.Cells(6).Value.ToString
If MainStudent.stdidTB.Text = "" Then
key = 0
Else
key = Convert.ToInt32(row.Cells(0).Value.ToString)
End If
End Sub
我希望代碼DateTimePicker1.Value = row.Cells(6).Value.ToString將日期回傳給 datetimepicker,但它回傳標題中的錯誤。任何人都可以協助任何相關代碼或解決問題的替代方法。
uj5u.com熱心網友回復:
如果可能,您應該使用資料系結。從一個類開始保存你的資料(也許你已經有了一個,但這是一個基本模型),
Private Class DataClass
Public Property Bid As Integer
Public Property BookTitle As String
Public Property [Date] As DateTime
End Class
并填充該模型的串列,并系結您的 DataGridView,
Dim data As New List(Of DataClass)
data.Add(New DataClass With {.Bid = 1, .BookTitle = "Title 1", .[Date] = DateTime.Now.AddDays(-1)})
data.Add(New DataClass With {.Bid = 2, .BookTitle = "Title 2", .[Date] = DateTime.Now})
IssueDGV.DataSource = data
現在您可以獲得保存資料的物件,并使用強名稱而不是索引。
Private Sub IssueDGV_CellMouseClick(sender As Object, e As DataGridViewCellMouseEventArgs) Handles IssueDGV.CellMouseClick
Dim row As DataGridViewRow = IssueDGV.Rows(e.RowIndex)
Dim item = DirectCast(row.DataBoundItem, DataClass)
Bidlbl.Text = item.Bid.ToString()
Booktitlelbl.Text = item.BookTitle
DateTimePicker1.Value = item.Date
End Sub
您的方法的一個問題是列索引與 DataGridView 的填充方式相關。如果您添加另一列,那么您可能需要更改索引,并且很難跟蹤每列的含義,甚至無法通知您需要更改索引。
我不知道您的 DataGridView 當前是如何填充的,但是如果您沒有支持物件并且在 UI 中存盤狀態,這絕不是一個好主意。UI 應該只用于資訊流,而不是狀態。
uj5u.com熱心網友回復:
我想在字串轉換為 DateTimePicker.Value 的程序中會發生一些事情。在將字串分配給“ DateTimePicker1.Value = ”之前嘗試轉換您的字串
*編輯首先嘗試洗掉值旁邊的 .ToString ,并檢查空值
這些鏈接可能會有所幫助。 https://docs.microsoft.com/en-us/dotnet/api/system.windows.forms.datetimepicker.value?view=windowsdesktop-5.0
https://www.educba.com/string-to-date-c-sharp/
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/324514.html
