Unable to cast object of type x to type x on setting dataSource to a table
-
Sonntag, 19. Februar 2012 22:14
Columns 0 & 1 are filled from a DataAdapter from Access Database and three are added. I had this working, but I changed it to check for the column "Feed" so I could add several Locations. At first this worked, but I did someething in perfecting it and it now fails after filling the first row of the datagridview (dgvFdMed). I ran a check and the table LotsTab has 8 rows filled. Column 1 & 2 are strings and the database appears they are fine. The added columns have just been created with no value. My plan is to enter the values and then use the data from the grid.Private Sub sfillGrid(ByVal Loc As String) Dim i As Integer Dim column As DataGridViewColumn Dim col As New DataColumn Dim SQL = "SELECT Location, LotNo FROM Lots WHERE Location LIKE '" & fParseString(Loc) & "';" StrComp = fGetStrComp() Dim CompConn As New OleDbConnection(StrComp) Dim CompAdapter As New OleDbDataAdapter(SQL, CompConn) Try CompAdapter.Fill(LotsTab) If LotsTab.Columns("Feed") Is Nothing Then LotsTab.Columns.Add("Feed", Type.GetType("System.Double")) LotsTab.Columns.Add("FeedDol", Type.GetType("System.Double")) LotsTab.Columns.Add("Med", Type.GetType("System.Double")) dgvFdMed.DataSource = LotsTab End If For i = 0 To 1 column = dgvFdMed.Columns(i) column.ReadOnly = True column.DefaultCellStyle.BackColor = Color.Gray column.DefaultCellStyle.ForeColor = Color.AntiqueWhite Next i 'dgvFdMed.AllowUserToAddRows = False 'dgvFdMed.AllowUserToDeleteRows = False 'dgvFdMed.AllowUserToOrderColumns = False 'dgvFdMed.AllowUserToResizeRows = False dgvFdMed.Columns(0).Width = 120 dgvFdMed.Columns(1).Width = 60 dgvFdMed.Columns(2).HeaderText = "Pounds Fed" dgvFdMed.Columns(3).HeaderText = "Feed Cost" dgvFdMed.Columns(4).HeaderText = "Med Cost" dgvFdMed.CurrentCell = dgvFdMed(2, 0) Catch ex As Exception MsgBox(ex.Message) End Try End Sub
Alle Antworten
-
Montag, 20. Februar 2012 00:13
which line are you getting the error on? I assume somewhere within this class you are instantiating a DataTable object LotsTab:
Dim LotsTab As New DataTable
I recreated your code in an app and simulated filling a datatable from the database, and I don't get any errors.
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load Dim LotsTab As New DataTable LotsTab.Columns.Add("Location", GetType(String)) LotsTab.Columns.Add("LotNo", GetType(String)) LotsTab.Rows.Add("LocA", "LotA1") LotsTab.Rows.Add("LocB", "LotB2") LotsTab.Rows.Add("LocC", "LotC3") LotsTab.Rows.Add("LocD", "LotD4") If LotsTab.Columns("Feed") Is Nothing Then LotsTab.Columns.Add("Feed", Type.GetType("System.Double")) LotsTab.Columns.Add("FeedDol", Type.GetType("System.Double")) LotsTab.Columns.Add("Med", Type.GetType("System.Double")) End If dgvFdMed.DataSource = LotsTab.DefaultView Dim column As DataGridViewColumn For i = 0 To 1 column = dgvFdMed.Columns(i) column.ReadOnly = True column.DefaultCellStyle.BackColor = Color.Gray column.DefaultCellStyle.ForeColor = Color.AntiqueWhite Next i dgvFdMed.Columns(0).Width = 120 dgvFdMed.Columns(1).Width = 60 dgvFdMed.Columns(2).HeaderText = "Pounds Fed" dgvFdMed.Columns(3).HeaderText = "Feed Cost" dgvFdMed.Columns(4).HeaderText = "Med Cost" dgvFdMed.CurrentCell = dgvFdMed(2, 0) End Sub- Als Antwort vorgeschlagen Mike FengMicrosoft Contingent Staff, Moderator Montag, 20. Februar 2012 10:18
-
Montag, 20. Februar 2012 02:44
Very strange.
It is giving me an error on dgvFdMed.DataSource = LotsTab and if I step past it, it posts one row on the dataviewgrid and gives another error on dgvFdMed.CurrentCell = dgvFdMed(2, 0)
I did not have LotsTab.defaultview and I had it within the if/then. However, I had tried it where yours is located. The reason I had it in the if/then is that I was going to add more rows from other locations.Thanks
-
Montag, 20. Februar 2012 04:00
try adding the line to instantiate a new datatable object as I show in my post within the sFillGrid method
-
Montag, 20. Februar 2012 17:25
Okay, I had Dim LotsTab as New DataTable at the first of the class because I plan to use this table elsewhere.
That said, I copied your code over into my Private Sub sfillGrid(ByVal Loc as String) commenting out all of my code. I receive the same error on dgvFdMed.DataSource= LotsTab.DefaultView and if I proceed on, at dgvFdMed.CurrentCell = dgvFdMed(2,0)
I don't know what is happening. As I said, I was populating the dgv and made some minor changes and took off and when I came back it was giving error. I don't remember exactly what I changed and don't have something like I had with VB6 where I can reverse changes.
I am using an Access Database, but your code doesn't use any database. I thought that, maybe, my references might impact it.
By the way, the reason that I am populating with code instead of binding the grid to the database, is that the user picks the database to bind. I had already tested for a corrupt database by trying a different database.
-
Montag, 20. Februar 2012 20:24Moderator
What is the message of the error?
Double check your column configuration in the DataGridView. Ensure that if you are using AutoGenerateColumns that there are no existing columns in the designer. If you have configured all of your columns in the designer, ensure that AutoGenerateColumns is set to False and double check the DataPropertyName for each column is spelled correctly and pointing to one of the column names in your data table.
Reed Kimble - "When you do things right, people won't be sure you've done anything at all"
-
Montag, 20. Februar 2012 22:28
Thanks. Let me describe exactly what I am doing. I am taking two columns from the database to the table (this generates their names) and then adding three columns that would not have values. Then I am binding the table to the datagridview which has no existing columns. The datagridview is on the form, but without columns. Doing it this way, I wouldn't think I would need to worry about the DataPropertyName. Maybe I am missing something.
When it was working, it appeared that there were two columns from the database that were populated and all of the other columns were blank.
I am a newby who is trying to get my vb6 programs over to 2010.
I can not see AutoGenerateColumns on my dataGridView. The DataPropertyName is not set as it is derived from the LotsTab table. I am setting the HeaderText, as you can see.
Maybe I should start fresh, but I can't see that I would design it differently.
-
Montag, 20. Februar 2012 23:20Moderator
That is what I understood you to be doing, other than where your columns come from...
Can you please tell us the text of the error you receive? Knowing exactly what the error is and precisely which code causes it can often lead directly to the cause.
I do not know where your DataGridView is getting its columns... if there are none in the designer, and the posted code does not create them, then either some other code does, or AutoGenerateColumns is set to true in code somewhere.
Has the grid been set to virtual mode, perhaps? I'm trying to guess at things which could cause an exception when setting the datasource to a table instance. Telling us the error message should eliminate the guessing.
Reed Kimble - "When you do things right, people won't be sure you've done anything at all"
-
Dienstag, 21. Februar 2012 00:04
Sorry, the last three columns are assigned in code (above) and do not have data. I am actually trying to use them as input fields to populate the table. The first two columns are coming from the database and are populated from it. But, as I said, I got the same errors running the Jwavila wrote.
I don't know how to set to virtual mode.
The error from drvFdMed.DataSource=LotsTab.DefaultView
and on
dgvFdMed.CurrentCell = dgvFdMed(2, 0)
is System.InvalidCastException was unhandled
Message=Unable to cast object of type 'System.EventArgs' to type 'System.Windows.Forms.DataGridViewCellEventArgs'.
Source=CM
StackTrace:
at WindowsApplication1.FeedMed._Lambda$__1(Object a0, EventArgs a1) in C:\Users\Jay\Documents\Visual Studio 2010\Projects\CM\CM\FeedMed.Designer.vb:line 0
at System.Windows.Forms.DataGridView.OnSelectionChanged(EventArgs e)
at System.Windows.Forms.DataGridView.FlushSelectionChanged()
at System.Windows.Forms.DataGridView.ClearSelection(Int32 columnIndexException, Int32 rowIndexException, Boolean selectExceptionElement)
at System.Windows.Forms.DataGridView.SetAndSelectCurrentCellAddress(Int32 columnIndex, Int32 rowIndex, Boolean setAnchorCellAddress, Boolean validateCurrentCell, Boolean throughMouseClick, Boolean clearSelection, Boolean forceCurrentCellSelection)
at System.Windows.Forms.DataGridView.MakeFirstDisplayedCellCurrentCell(Boolean includeNewRow)
at System.Windows.Forms.DataGridView.OnRowCollectionChanged_PostNotification(Boolean recreateNewRow, Boolean allowSettingCurrentCell, CollectionChangeAction cca, DataGridViewRow dataGridViewRow, Int32 rowIndex)
at System.Windows.Forms.DataGridViewRowCollection.OnCollectionChanged_PostNotification(CollectionChangeAction cca, Int32 rowIndex, Int32 rowCount, DataGridViewRow dataGridViewRow, Boolean changeIsDeletion, Boolean changeIsInsertion, Boolean recreateNewRow, Point newCurrentCell)
at System.Windows.Forms.DataGridViewRowCollection.OnCollectionChanged(CollectionChangeEventArgs e, Int32 rowIndex, Int32 rowCount)
at System.Windows.Forms.DataGridViewRowCollection.AddInternal(DataGridViewRow dataGridViewRow)
at System.Windows.Forms.DataGridView.RefreshRows(Boolean scrollIntoView)
at System.Windows.Forms.DataGridView.RefreshColumnsAndRows()
at System.Windows.Forms.DataGridView.OnDataSourceChanged(EventArgs e)
at System.Windows.Forms.DataGridView.set_DataSource(Object value)
at WindowsApplication1.FeedMed.sfillGrid(String Loc) in C:\Users\Jay\Documents\Visual Studio 2010\Projects\CM\CM\FeedMed.vb:line 193
at WindowsApplication1.FeedMed.cbLocation_SelectedIndexChanged(Object sender, EventArgs e) in C:\Users\Jay\Documents\Visual Studio 2010\Projects\CM\CM\FeedMed.vb:line 69
at System.Windows.Forms.ComboBox.OnSelectedIndexChanged(EventArgs e)
at System.Windows.Forms.ComboBox.WmReflectCommand(Message& m)
at System.Windows.Forms.ComboBox.WndProc(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
at System.Windows.Forms.UnsafeNativeMethods.SendMessage(HandleRef hWnd, Int32 msg, IntPtr wParam, IntPtr lParam)
at System.Windows.Forms.Control.SendMessage(Int32 msg, IntPtr wparam, IntPtr lparam)
at System.Windows.Forms.Control.ReflectMessageInternal(IntPtr hWnd, Message& m)
at System.Windows.Forms.Control.WmCommand(Message& m)
at System.Windows.Forms.Control.WndProc(Message& m)
at System.Windows.Forms.ScrollableControl.WndProc(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
at System.Windows.Forms.UnsafeNativeMethods.CallWindowProc(IntPtr wndProc, IntPtr hWnd, Int32 msg, IntPtr wParam, IntPtr lParam)
at System.Windows.Forms.NativeWindow.DefWndProc(Message& m)
at System.Windows.Forms.Control.DefWndProc(Message& m)
at System.Windows.Forms.Control.WmCommand(Message& m)
at System.Windows.Forms.Control.WndProc(Message& m)
at System.Windows.Forms.ComboBox.WndProc(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID, Int32 reason, Int32 pvLoopData)
at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
at Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.OnRun()
at Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.DoApplicationModel()
at Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.Run(String[] commandLine)
at WindowsApplication1.My.MyApplication.Main(String[] Args) in 17d14f5c-a337-4978-8281-53493378c1071.vb:line 81
at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
InnerException:Thanks
- Bearbeitet jjobcorp Dienstag, 21. Februar 2012 00:05
-
Dienstag, 21. Februar 2012 00:28
To narrow it down:
- In FeedMed.vb, line 193, you are setting the datasource of the datagridview.
- This indirectly calls the datagridview's OnSelectionChanged method.
- In OnSelectionChanged, one of your lambda expressions in FeeMed.vb is evaluated.
Do you handle the DataGridView's SelectionChanged event? If you do, how did you setup the event handler? Using AddHandler or by using a WithEvents variable? If it's the former, please post the AddHandler code. Also post the code of the SelectionChanged event handler.
Is Option Strict enabled? If not, do it. If there are compile errors, fix them first.
Armin
- Als Antwort markiert jjobcorp Dienstag, 21. Februar 2012 14:05
-
Dienstag, 21. Februar 2012 01:52Moderator
Further to Armin's reply, we can look at this part of the stack trace:
at WindowsApplication1.FeedMed._Lambda$__1(Object a0, EventArgs a1) in
In conjunction with the error message we can guess that you have some in-line sub or function declared with the parameters a0 of type Object and a1 of type EventArgs.
Assuming that the values are valid, then it may be that you need to be sure you are passing an instance of System.Windows.Forms.DataGridViewCellEventArgs to the a1 parameter and not just an EventArgs instance.
If you can show the code for OnSelectionChanged we can probably disect this further.
Reed Kimble - "When you do things right, people won't be sure you've done anything at all"
-
Dienstag, 21. Februar 2012 14:12Boy, this is the answer. I can not thank you enough. I had added a dgvFdMed_SelectionChanged. I don't know what code blew it up, but I don't have this code where it needs to be, anyway. I may pester you guys again if I can't make progress on this. YOu got me out of a week long bog and I really appreciate it.
-
Dienstag, 21. Februar 2012 14:37You're welcome!
Armin

