Results 1 to 3 of 3

Thread: [RESOLVED] GridView to DataTable

  1. #1

    Thread Starter
    Hyperactive Member
    Join Date
    Mar 2006
    Location
    Madrid
    Posts
    325

    Resolved [RESOLVED] GridView to DataTable

    Is there an easy way to pass data from a GridView to a DataTable,..??

    I have a loaded GridView,....

    Code:
    DataTable dt = new DataTable();
    
    foreach (GridViewRow dr in GridView1.Rows)
            {
                DataRow testDr = (dataRow)dr ,.... I tried this and it didnīt work,.
                
            }
    Thanks,
    Last edited by Rauland; Jun 20th, 2007 at 04:11 AM. Reason: code

  2. #2
    Smitten by reality Harsh Gupta's Avatar
    Join Date
    Feb 2005
    Posts
    2,938

    Re: GridView to DataTable

    It may vary depending upon the DataSource of your GridView.

    Try
    C# Code:
    1. //If DataSource of GridView1 is a DataTable
    2. DataTable dt = (DataTable)GridView1.DataSource;
    3.  
    4. //If DataSource of GridView1 is a DataView
    5. DataView dv = (DataView)GridView1.DataSource;
    In your code, you cannot convert GridViewRow to DataRow. You have to manually create columns first, then loop through all the rows. Within this loop, you would need to loop through all the columns of the row and copy it to the DataRow that you are creating.
    c# Code:
    1. //This is just a Psuedocode
    2.  
    3. DataTable dt = new DataTable();
    4.  
    5. //Add columns here
    6. dt.Columns.Add(); //or something similar
    7.  
    8. //go on till all the columns are added
    9.  
    10. //loop and second loop
    11. foreach(GridViewRow gvr in GridView1.Rows)
    12. {
    13.    DataRow dr = dt.NewRow();
    14.    
    15.    //second loop - looping all columns
    16.    for(int i = 0; i < gvr.Rows.Count; ++i)
    17.    {
    18.       dr[i] = gvr.Cells[i].Text;
    19.    }
    20. }
    Hope it helps you.
    Show Appreciation. Rate Posts.

  3. #3

    Thread Starter
    Hyperactive Member
    Join Date
    Mar 2006
    Location
    Madrid
    Posts
    325

    Re: GridView to DataTable

    Cheers!

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