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
I want the code DateTimePicker1.Value = row.Cells(6).Value.ToString
to return the date to the datetimepicker but it returns the error in the title. May anyone assist with any relevant code or alternate way to approach the problem.
CodePudding user response:
You should use databindings if possible. Start with a class to hold your data (maybe you already have one but this is a basic model),
Private Class DataClass
Public Property Bid As Integer
Public Property BookTitle As String
Public Property [Date] As DateTime
End Class
and populate a list of that model, and bind your 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
and now you can get the object which holds your data, and use strong names instead of indices.
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
One problem with your approach is that the column indices are tied to how your DataGridView is populated. If you add another column, then you would need to potentially change the indices, and it is difficult to keep track of what each means, and to even be notified you need to change the indices.
I don't know how your DataGridView is currently populated but if you don't have a backing object and are storing state in the UI, that is never a good idea. The UI should only be used for information flow, not state.
CodePudding user response:
I imagine there's something going on during the string conversion to DateTimePicker.Value. Try Converting your string before assigning it to " DateTimePicker1.Value = "
*edit try removing the .ToString next to value first, and check for null values
these links may be helpful. https://docs.microsoft.com/en-us/dotnet/api/system.windows.forms.datetimepicker.value?view=windowsdesktop-5.0