Share via

Tryparse Value According to Datagridview Column Valuetype?

Hobbyist_programmer 621 Reputation points
2021-08-26T14:11:41.993+00:00

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
Developer technologies | VB
0 comments No comments

1 answer

Sort by: Most helpful
  1. Michael Taylor 61,221 Reputation points
    2021-08-26T14:47:29.417+00:00

    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  
    

    Was this answer helpful?

    0 comments No comments

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.