Results 1 to 3 of 3

Thread: [RESOLVED]Getting Column Names, Col and row count from datagrid

  1. #1

    Thread Starter
    Hyperactive Member
    Join Date
    Jan 2002
    Posts
    425

    Resolved [RESOLVED]Getting Column Names, Col and row count from datagrid

    Hi,

    I am trying to get the column names and col/row count from a datagrid but it seems that i am stucked. I have tried the following which i got from searching the forum but i got an error : An unhandled exception of type 'System.InvalidCastException' occurred in WindowsApplication1.exe
    Additional information: Specified cast is not valid.


    VB Code:
    1. 'Dg is a datagrid
    2.  
    3.         Dim dt As DataTable
    4.         dt = Dg.DataSource
    5.         MsgBox(dt.Rows.Count.ToString)
    6.         MsgBox(dt.Columns.Count.ToString)

    thanks for your time
    Last edited by hyper88; Mar 21st, 2006 at 02:47 AM.

  2. #2
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    111,221

    Re: Getting Column Names, Col and row count from datagrid

    Have you actually assigned a DataTable to the DataSource of the grid? If so you should use:
    VB Code:
    1. dt = DirectCast(dg.DataSource, DataTable)
    If not then you'll need to get the object from the DataSource as it is and get the DataTable from that. Here are examples if you've used a DataSet or a DataView as the DataSource:
    VB Code:
    1. 'For DataSet.
    2. dt = DirectCast(dg.DataSource, DataSet).Tables(dg.DataMember)
    3.  
    4. 'For DataView.
    5. dt = DirectCast(dg.DataSource, DataView).Table
    Last edited by jmcilhinney; Mar 21st, 2006 at 02:33 AM. Reason: Fixed first code snippet
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

  3. #3

    Thread Starter
    Hyperactive Member
    Join Date
    Jan 2002
    Posts
    425

    Re: Getting Column Names, Col and row count from datagrid

    Ok..got it.. thanks jmcilhinney for the help.
    You have been really helpful as i see that you try to help whenever you can.

    thanks to all the guys who took their time to read my problems. Really appreciate it.

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