By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
440,649 Members | 2,154 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 440,649 IT Pros & Developers. It's quick & easy.

When trying to capture value of checkbox I get a caste error

100+
P: 347
I have a form that has a datatable on it with the following code:

Expand|Select|Wrap|Line Numbers
  1. Imports System.Data.SqlClient
  2. Imports System.Data
  3. Public Class AddHoliday
  4.     Private Sub AddHoliday_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
  5.         'TODO: This line of code loads data into the 'MDRDataSet5.scratchpad2' table. You can move, or remove it, as needed.
  6.         Me.Scratchpad2TableAdapter.Fill(Me.MDRDataSet5.scratchpad2)
  7.     End Sub
  8.  
  9.     Private Sub DataGridView1_DataError(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewDataErrorEventArgs) Handles DataGridView1.DataError
  10.         Dim msg = String.Format("DataError occurred:\{0}\{1}\DataErrorContext: {2}", e.Exception.GetType().ToString(), e.Exception.Message, e.Context)
  11.         MessageBox.Show(msg)
  12.     End Sub
  13.     Private Sub DataGridView1_CellContentClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DataGridView1.CellContentClick
  14.         Dim ch1 As New DataGridViewCheckBoxCell()
  15.         ch1 = DirectCast(DataGridView1.Rows(DataGridView1.CurrentRow.Index).Cells(0), DataGridViewCheckBoxCell)
  16.  
  17.         If ch1.Value Is Nothing Then
  18.             ch1.Value = False
  19.         End If
  20.         Select Case ch1.Value.ToString()
  21.             Case "True"
  22.                 ch1.Value = False
  23.                 Exit Select
  24.             Case "False"
  25.                 ch1.Value = True
  26.                 Exit Select
  27.         End Select
  28.     End Sub
  29.  
and when I try to debug it I get the error "Unable to cast object of type 'System.Windows.Forms.DataGridViewTextBoxCell' to type 'System.Windows.Forms.DataGridViewCheckBoxCell'."

The line of code that's throwing this error is
Expand|Select|Wrap|Line Numbers
  1.  ch1 = DirectCast(DataGridView1.Rows(DataGridView1.CurrentRow.Index).Cells(0), DataGridViewCheckBoxCell)
  2.  
can someone assist me with this error?

Thank you

Doug
Apr 11 '11 #1
Share this Question
Share on Google+
1 Reply


P: 24
Hello, Doug,

From the message, it sounds like .Cells(0) is returning a value of type DataGridViewTextBoxCell. So try changing the declaration of ch1 to that type. That is:

Dim ch1 As New DataGridViewTextBoxCell()

Cheers,
Randy
Apr 12 '11 #2

Post your reply

Sign in to post your reply or Sign up for a free account.