Results 1 to 12 of 12

Thread: Weird Exception when showing Data in DataGridView

  1. #1

    Thread Starter
    Junior Member
    Join Date
    Jan 2017
    Posts
    18

    Resolved Weird Exception when showing Data in DataGridView

    Hi everyone! I'm new as a registered user but I've been reading this forum for help for the last 2 months, I have the following issue:

    I have a Form, where I load a Query stored in my DataSet, I use a DataGridView to show the query (my idea is to use the selected index on the DataGridView in order to allow the user to edit that row), I use the following code:

    Public Table As DataTable

    When the form loads I run this code:

    Table = DetProdConsultaTableAdapter.GetDetalleProductos(ID_Orden)
    DataGridView1.DataSource = Table


    But when the form loads, I get the following exception:
    Unable to cast object 'System.EventArgs' to type 'System.Windows.Forms.DataGridViewCellEventArgs'

    on the line where I set the DataGridView's Data Source

    I hope I've been clear enough

    Thanks a lot!
    Last edited by nicomanzur; Jan 4th, 2017 at 10:53 AM. Reason: Solution found

  2. #2
    Frenzied Member PlausiblyDamp's Avatar
    Join Date
    Dec 2016
    Location
    Newport, UK
    Posts
    1,430

    Re: Weird Exception when showing Data in DataGridView

    It sounds like you also have an eventhandler on the DataGridView (check for any Subs that have a Handles clause at the end) that has an incorrect signature. It might be worth removing the event handlers one at a time until the error goes away, that should at least identify the problematic one.

  3. #3
    .NUT jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    107,130

    Re: Weird Exception when showing Data in DataGridView

    If you use the VS Help menu to open the MSDN documentation, you can read the topic for the DataGridViewCellEventArgs class and it will tell you what events that type is used for. You have a method that is handling an event that is not in that list but is declaring the 'e' parameter as that type.

    By convention, all event handlers in .NET have two parameters: 'sender' declared as type Object and 'e' declared as type EventArgs or some type derived from it. The first parameter refers to the object that raised the event while the second parameter refers to an object that contains the data for the event. For instance, if you click a Button then, in its Click event handler, the 'sender' will be the Button that was clicked and 'e' will be an EventArgs object that contains mothing of interest because there's no data associated with that event. In the CellClick event handler of a DataGridView, the 'sender' will be the DataGridView containing the cell that was clicked while 'e' will be a DataGridViewCellEventArgs that contains the column and row indexes of the cell that was clicked and some other stuff too.

    You are handling an event that has a signature like the first with a method that has a signature like the second. When the event is raised, an EventArgs object is passed to the 'e' parameter but that parameter is declared as type DataGridViewCellEventArgs and so it fails. This is an example of why, until you know what you're doing, you should ALWAYS let the IDE generate your event handlers for you. What may have happened here is that you did that for some event and then you decided to handle a different event with the same method. In that case, what you should have done was let the IDE generate a new event handler and then moved your code and deleted the old one.

  4. #4

    Thread Starter
    Junior Member
    Join Date
    Jan 2017
    Posts
    18

    Re: Weird Exception when showing Data in DataGridView

    Thanks both of you, I tried but could not fin what may be generating the problem, so I decided to copy & paste the form that generates the issue:

    Code:
    Public Class frmPrueba
        Public Vista As DataGridView
        Public IDOrden As Integer
        Public Tabla As DataTable
        Private Sub frmPrueba_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
            IDOrden = frmListarOrdenes.ID_Orden
            Tabla = New DataTable
            Tabla = DetProdConsultaTableAdapter.GetDetalleProductos(ID_Orden)
            SeroqDataSet1.EnforceConstraints = False
            DataGridView1.AutoGenerateColumns = True
            DataGridView1.DataSource = Tabla
            DataGridView1.Columns.Item(0).Visible = False
            DataGridView1.Columns.Item(10).Visible = False
            DataGridView1.Columns.Item(11).Visible = False
            DataGridView1.Refresh()
        End Sub
    
        Private Sub DataGridView1_CellContentClick(sender As System.Object, e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DataGridView1.CellContentClick, DataGridView1.SelectionChanged
            Dim ID_Relacion, ID_Material, ID_Calidad As Integer
            Dim IDs = New Integer(2) {}
            Dim i As Integer = DataGridView1.CurrentRow.Index
            ID_Relacion = DataGridView1.Item(6, i).Value
            IDs = Funciones.ObtieneID(ID_Relacion)
            'El elemento 0 contiene el ID_Calidad y el 1 el ID_Material
            ID_Calidad = IDs(0)
            ID_Material = IDs(1)
            txtAlto.Text = DataGridView1.Item(3, i).Value.ToString
            txtAncho.Text = DataGridView1.Item(4, i).Value.ToString
            txtCantidad.Text = DataGridView1.Item(5, i).Value.ToString
            cmbCalidad.SelectedValue = ID_Calidad
            cmbMaterial.SelectedValue = ID_Material
        End Sub
    End Class
    I hope this helps, thank you very much!
    Last edited by Shaggy Hiker; Jan 3rd, 2017 at 11:43 AM. Reason: Added CODE tags

  5. #5
    PowerPoster techgnome's Avatar
    Join Date
    May 2002
    Posts
    33,428

    Re: Weird Exception when showing Data in DataGridView

    looks like John was right:
    Quote Originally Posted by jmcilhinney
    What may have happened here is that you did that for some event and then you decided to handle a different event with the same method. In that case, what you should have done was let the IDE generate a new event handler and then moved your code and deleted the old one.

    this line:
    Private Sub DataGridView1_CellContentClick(sender As System.Object, e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DataGridView1.CellContentClick, DataGridView1.SelectionChanged

    is handling TWO events... but the event args that's being passed in is only valid for ONE of those events.

    -tg
    * I don't respond to private (PM) requests for help. It's not conducive to the general learning of others.*
    * I also don't respond to friend requests. Save a few bits and don't bother. I'll just end up rejecting anyways.*
    * How to get EFFECTIVE help: The Hitchhiker's Guide to Getting Help at VBF - Removing eels from your hovercraft *
    * How to Use Parameters * Create Disconnected ADO Recordset Clones * Set your VB6 ActiveX Compatibility * Get rid of those pesky VB Line Numbers * I swear I saved my data, where'd it run off to??? *

  6. #6
    .NUT jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    107,130

    Re: Weird Exception when showing Data in DataGridView

    Quote Originally Posted by techgnome View Post
    looks like John was right:



    this line:
    Private Sub DataGridView1_CellContentClick(sender As System.Object, e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DataGridView1.CellContentClick, DataGridView1.SelectionChanged

    is handling TWO events... but the event args that's being passed in is only valid for ONE of those events.

    -tg
    It seems very strange that you should want to do anything on both of those events. If you really do then what you should be doing is creating two separate event handlers with their appropriate signatures and then, from both, calling a single method that does the common work.

    More likely though, is that you should be handling some other - and only one other - event. What are you actually trying to achieve? My guess is that you should be handling the RowEnter event. That will allow you to do something each time a new row is about to receive focus. If the focus changes to a different cell within the same row, whether by mouse or keyboard, then nothing will happen.

    Looking more closely at your code though, it looks like you shouldn't be handling any event at all. You're binding a DataTable to the grid. You should be binding that same DataTable to your TextBoxes and such too. That way, selecting a row in the grid will automatically populate the other controls with the data from the DataRow that the selected grid row is bound to.

    Even if you don't bind the other controls, you should still bind the DataTable to a BindingSource and that to the grid. You can then handle the CurrentChanged event of the BindingSource to be notified of when the row selection changes. You'd then get the data via the Current property of the BindingSource.

  7. #7
    PowerPoster techgnome's Avatar
    Join Date
    May 2002
    Posts
    33,428

    Re: Weird Exception when showing Data in DataGridView

    I didn't look at it that closely... but it looks like the OP wants to fill some text boxes with data from the currently selected row ... I'd just use the SelectionChange ... there's no need to re-load them on every single cell click. That said, I'd probably go the same route and just bind everything to the same BindingSource and use that to keep it all in synch. It's going to make updating a lot easier too.

    -tg
    * I don't respond to private (PM) requests for help. It's not conducive to the general learning of others.*
    * I also don't respond to friend requests. Save a few bits and don't bother. I'll just end up rejecting anyways.*
    * How to get EFFECTIVE help: The Hitchhiker's Guide to Getting Help at VBF - Removing eels from your hovercraft *
    * How to Use Parameters * Create Disconnected ADO Recordset Clones * Set your VB6 ActiveX Compatibility * Get rid of those pesky VB Line Numbers * I swear I saved my data, where'd it run off to??? *

  8. #8
    Super Moderator Shaggy Hiker's Avatar
    Join Date
    Aug 2002
    Location
    Idaho
    Posts
    36,257

    Re: Weird Exception when showing Data in DataGridView

    Looks like a leftover from a design change, to me.
    My usual boring signature: Nothing

  9. #9
    .NUT jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    107,130

    Re: Weird Exception when showing Data in DataGridView

    Quote Originally Posted by techgnome View Post
    I'd just use the SelectionChange
    SelectionChanged isn't really the appropriate event though. The point of SelectionChanged is, as the name suggests, knowing when the selection changes. That event should only really be used when you want to do something with the SelectedCells, SelectedColumns or SelectedRows property. If you move from cell to cell within the same row then you're going to see multiple instances of this event raised. The code indicates that the OP is interested in the current row, so there's no point doing anything if the current row hasn't changed. That's why a row-based event is more appropriate in this case.

  10. #10
    Hyperactive Member
    Join Date
    Sep 2004
    Posts
    477

    Re: Weird Exception when showing Data in DataGridView

    Personally I wouldn't mess with loading data from the DGV to textboxes for editing. I would handle the following two events of the DGV to allow the user to directly edit the DGV and have it save the data.

    1. DataGridView1.CellValueChanged - Use this to set an integer flag (initialized as -1) to the row number that you edited. That lets the program know a cell has been changed and in which row.
    2. DataGridView1.RowEnter - When this fires check the flag, if not Nothing, then validate and save the data from the specified row to the DB and set the flag back to -1.

    Now one might think that it would be smarter to use the RowLeave event instead of RowEnter. Unfortunately the way VB works is that the RowLeave event will fire BEFORE the CellValueChanged event if you change a cell then change rows without changing to a different cell on the same row first. Oh and you should check to make sure the rows are not nothing before trying to set the flag because CellValueChanged will fire as the form loads and will cause errors trying to set the flag to a row on form load when no rows yet exist.

    One final note, you should probably also use a Boolean flag when programmatically loading the data to prevent these events from actually doing anything during the initial data load.
    Last edited by Maverickz; Jan 4th, 2017 at 02:08 AM.

  11. #11
    .NUT jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    107,130

    Re: Weird Exception when showing Data in DataGridView

    Quote Originally Posted by Maverickz View Post
    Personally I wouldn't mess with loading data from the DGV to textboxes for editing. I would handle the following two events of the DGV to allow the user to directly edit the DGV and have it save the data.

    1. DataGridView1.CellValueChanged - Use this to set an integer flag (initialized as -1) to the row number that you edited. That lets the program know a cell has been changed and in which row.
    2. DataGridView1.RowEnter - When this fires check the flag, if not Nothing, then validate and save the data from the specified row to the DB and set the flag back to -1.

    Now one might think that it would be smarter to use the RowLeave event instead of RowEnter. Unfortunately the way VB works is that the RowLeave event will fire BEFORE the CellValueChanged event if you change a cell then change rows without changing to a different cell on the same row first. Oh and you should check to make sure the rows are not nothing before trying to set the flag because CellValueChanged will fire as the form loads and will cause errors trying to set the flag to a row on form load when no rows yet exist.

    One final note, you should probably also use a Boolean flag when programmatically loading the data to prevent these events from actually doing anything during the initial data load.
    I couldn't disagree more. There's already a bound DataTable here so why would you need to track which row has changed when that DataTable will track changes already? Whether you want to save changes as they're made or in a batch, you can simply pass the DataTable to the Update method of your data adapter and it will take care of the rest. Also, if you bind via a BindingSource then you just handle the CurrentChanged event. You may need to call EndEdit to be sure any pending edit is committed first although I'm not sure.

  12. #12

    Thread Starter
    Junior Member
    Join Date
    Jan 2017
    Posts
    18

    Re: Weird Exception when showing Data in DataGridView

    Hi guys, thanks for all the answers! I'll explain a little bit the code, and where it came from. To begin with it's my first big programming project (and the first one with a possibility of selling it to a Graphics Design company), my only experience is 3 months of learning VS2010 at College 4 years ago, so a lot of the things I want to achieve, I have to achieve them the hard way, using some basic ideas and solutions (Such as copying the information from the DataGridView into a TextBox in order to update a row) because I have no in depth formation on VS2010 and best practices.

    The code I posted is a Form where the user edits a "Work form", where he can edit the type of material he will print, the size of the sign or whatever he wants to print and the amount of signs for example. To show the user the name of the material he is going to be working with, the name of the quality he will set the printer (regular or medium in my case) I had to create a quite complex query and use it to load all the information in a Table Adapter, my problem is this query receives an ID, so when I set the DataGridView to be connected to a Binding Source, I see a grey DataGridView with no information and I don't know how I can tell the Binding Source the ID I want to be used to display only certain rows.

    To sum up, I want to thank jmcilhinney because I corrected the code and now the form is working (I'm reading all you guys' replies and trying to apply them in order to improve my knowledge and my code).

    Thank you very much,

    Any comments and suggestions will be well received!

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width