question

Hobbyistprogrammer-7674 avatar image
0 Votes"
Hobbyistprogrammer-7674 asked cooldadtx answered

Tryparse Value According to Datagridview Column Valuetype?

Hallo I have a following code , which paste the clipboard values to datagridview. I want to include a step to check if the value matches the datagridview column type then paste otherwise just skip that value. I can get the column value type but dont know how to parse the value according to column type.

  Dim dgv As DataGridView = CType(dgvObj, DataGridView)
    
         'Show Error if no cell is selected
         If dgv.SelectedCells.Count = 0 Then
             MessageBox.Show("Please select a cell", "Paste", MessageBoxButtons.OK, MessageBoxIcon.Warning)
             Return
         End If
    
    
         'Get the starting Cell
         Dim startCell As DataGridViewCell = GetStartCell(dgv)
    
         'Get the clipboard value in a dictionary
         Dim cbValue As Dictionary(Of Integer, Dictionary(Of Integer, String)) = ClipBoardValues(Clipboard.GetText())
         Dim iRowIndex As Integer = startCell.RowIndex
    
         For Each rowKey As Integer In cbValue.Keys
             Dim iColIndex As Integer = startCell.ColumnIndex
    
             For Each cellKey As Integer In cbValue(rowKey).Keys
    
                 'Check if the index is within the limit
                 If iColIndex <= dgv.Columns.Count - 1 AndAlso iRowIndex <= dgv.Rows.Count - 1 Then
                     Dim cell As DataGridViewCell = dgv(iColIndex, iRowIndex)    
                      
    
                     Dim Valtype As Type = dgv.Columns(iColIndex).ValueType
    
    
                     If Not cell.ReadOnly Then    
    
                         TryCast(cbValue(rowKey)(cellKey), Valtype)------------------check or convert value type
    
                         cell.Value = cbValue(rowKey)(cellKey)
                     End If
    
                 End If
    
                 iColIndex += 1
             Next
    
             iRowIndex += 1
         Next
dotnet-visual-basic
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

1 Answer

cooldadtx avatar image
0 Votes"
cooldadtx answered

Assuming you stick with primitives then consider using Convert.ChangeType. Under the hood it use IConvertible to convert from the given object to the given type, but of course it can fail so you'll need to wrap it in Try-Catch. Nevertheless it'll attempt to convert to the type you specify and since it is general purpose you don't really need to worry about the conversion yourself, you just get an object back.

Try
   cell.Value = Convert.ChangeType(cbValue(rowKey)(cellKey), Valtype)   
Catch 
  'Conversion failed
End Try

5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.