Gridview row.cells Unable to cast checkbox as textbox

Hutty 20 Reputation points
2024-06-12T13:33:51.9166667+00:00

I have this Gridview where I'm updating a SQL table. Everything works fine until I come across a column that has checkboxes. I'm getting an error message stating unable to cast/convert checkbox to textbox. Here are the lines in question.

Dim columnValue As String = CType(row.Cells(i).Controls(0), TextBox).Text

String.Format(" WHERE {0} = '{1}'", CType(GV1.HeaderRow.Cells(1).Controls(0), LinkButton).Text, CType(row.Cells(1).Controls(0), TextBox).Text)

Thanks in advance

Developer technologies .NET Other
0 comments No comments
{count} votes

Accepted answer
  1. Anonymous
    2024-06-13T05:33:52.01+00:00

    Hi @Hutty , Welcome to Microsoft Q&A,

    The error you're encountering is due to trying to cast a control that is not a TextBox into a TextBox. In your GridView, some cells contain CheckBox controls instead of TextBox controls. You need to check the type of control in each cell before attempting to cast it.

    Dim columnValue As String
    
    For Each cell As TableCell In row.Cells
        For Each ctrl As Control In cell.Controls
            If TypeOf ctrl Is TextBox Then
                columnValue = CType(ctrl, TextBox).Text
            ElseIf TypeOf ctrl Is CheckBox Then
                columnValue = CType(ctrl, CheckBox).Checked.ToString()
            End If
        Next
    Next
    
    Dim whereClause As String = String.Format(" WHERE {0} = '{1}'", CType(GV1.HeaderRow.Cells(1).Controls(0), LinkButton).Text, GetControlValue(row.Cells(1).Controls(0)))
    
    Private Function GetControlValue(control As Control) As String
        If TypeOf control Is TextBox Then
            Return CType(control, TextBox).Text
        ElseIf TypeOf control Is CheckBox Then
            Return CType(control, CheckBox).Checked.ToString()
        Else
            Return String.Empty
        End If
    End Function
    
    

    Best Regards,

    Jiale


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment". 

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


0 additional answers

Sort by: Most helpful

Your answer

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