locked
Convert DataGridView to DataSet or DataTable

    Question

  • Hi,

    i want to convert to datagridview to dataset

    to add the dataset in dataview

    in my code i am  binding the data from the list collection to datagridview

    dgvEmp.DataSource = Emp_BL.LoadEmployees ( Emp_DTO )

    here Emp_BL.LoadEmployees ( Emp_DTO )  returns   List<Emp_DTO>

    waiting for reply.......




    • Edited by Kumar Jalli Wednesday, July 04, 2012 6:44 AM
    Wednesday, July 04, 2012 6:19 AM

Answers

  • Wednesday, July 04, 2012 6:59 AM
  • Hello, the following VS2010 demo creates a list of a class which becomes the DataSource of a BindingSource where the BindingSource is assigned as the DataSource to a DataGridView.

    In Button1 click event a LINQ statement cast the BindingSource DataSource to a List(Of Customer) which is exactly what it is as we know from loading it in the load event. The Select New in this case is used to create a DataTable using a language extension method. Once the dt variable is of type DataTable which is placed into a DataSet. Next we traverse thru the new DataTable and create a string which shows three rows of two fields in a MessageBox. You could also cast the DataGridView DataSource in the LINQ statement but I see no reason why as usually a BinidingSource is public to your form, same as a DataGridView.

    If using VS2008 you will need to modifiy the code as in line continuation chars and expanding properties in the Customer class.

    Hope this helps.

    Form code

    Public Class Form1
        WithEvents bsCustomers As New BindingSource
        WithEvents DataSet1 As New DataSet
        Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
            Dim MyCustomerList As New List(Of Customer)
            MyCustomerList.Add(New Customer With {.Identifier = 1, .Name = "AAAA"})
            MyCustomerList.Add(New Customer With {.Identifier = 2, .Name = "BBBB"})
            MyCustomerList.Add(New Customer With {.Identifier = 3, .Name = "CCCC"})
            bsCustomers.DataSource = MyCustomerList
            DataGridView1.DataSource = bsCustomers
        End Sub
        Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
            Dim sb As New System.Text.StringBuilder
            Dim dt =
                (
                    From T In CType(bsCustomers.DataSource, List(Of Customer))
                    Select New With {.Identifier = T.Identifier, .Name = T.Name}
                ).ToDataTable
            dt.TableName = "Customers"
            DataSet1.Tables.Add(dt)
            For Each row As DataRow In DataSet1.Tables("Customers").Rows
                sb.AppendLine(
                    String.Format("[{0}] [{1}]",
                                  row("Identifier").ToString,
                                  row("Name").ToString)
                )
            Next
            MessageBox.Show(sb.ToString)
        End Sub
    End Class
    Public Class Customer
        Public Property Identifier As Integer
        Public Property Name As String
        Public Sub New()
        End Sub
    End Class

    Code module (this code must be in a code module)

        <System.Diagnostics.DebuggerStepThrough()> _
        <System.Runtime.CompilerServices.Extension()> _
        Public Function ToDataTable(Of T)(ByVal sender As IEnumerable(Of T)) As DataTable
            Dim dt As New DataTable
            Dim FirstRecord = sender.First ' used to create column definition for the table
            For Each pi In FirstRecord.GetType.GetProperties
                dt.Columns.Add(pi.Name, pi.GetValue(FirstRecord, Nothing).GetType)
            Next
            ' Populate the table with data
            For Each result In sender
                Dim nr = dt.NewRow
                For Each pi In result.GetType.GetProperties
                    nr(pi.Name) = pi.GetValue(result, Nothing)
                Next
                dt.Rows.Add(nr)
            Next
            Return dt
        End Function


    KSG

    Thursday, July 05, 2012 3:48 AM

All replies

  • Hi,

    do as follows

               DataTable dtFromGrid = new DataTable();
                dtFromGrid = dataGridView1.DataSource as DataTable;


    PS.Shakeer Hussain

    Wednesday, July 04, 2012 6:24 AM
  • Hi Syed Thank you for reply

    your c# code i converted into vb.net code and used it but it returns nothing to datatable

    here is the converted code

      Dim dt As New DataTable()
      dt = TryCast(DataGridView1.DataSource, DataTable)

    Wednesday, July 04, 2012 6:46 AM
  • Hi,

    Check the below link, may it helps you

    http://www.dotnetperls.com/convert-list-datatable


    PS.Shakeer Hussain

    Wednesday, July 04, 2012 6:53 AM
  • Wednesday, July 04, 2012 6:59 AM
  • Hello, the following VS2010 demo creates a list of a class which becomes the DataSource of a BindingSource where the BindingSource is assigned as the DataSource to a DataGridView.

    In Button1 click event a LINQ statement cast the BindingSource DataSource to a List(Of Customer) which is exactly what it is as we know from loading it in the load event. The Select New in this case is used to create a DataTable using a language extension method. Once the dt variable is of type DataTable which is placed into a DataSet. Next we traverse thru the new DataTable and create a string which shows three rows of two fields in a MessageBox. You could also cast the DataGridView DataSource in the LINQ statement but I see no reason why as usually a BinidingSource is public to your form, same as a DataGridView.

    If using VS2008 you will need to modifiy the code as in line continuation chars and expanding properties in the Customer class.

    Hope this helps.

    Form code

    Public Class Form1
        WithEvents bsCustomers As New BindingSource
        WithEvents DataSet1 As New DataSet
        Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
            Dim MyCustomerList As New List(Of Customer)
            MyCustomerList.Add(New Customer With {.Identifier = 1, .Name = "AAAA"})
            MyCustomerList.Add(New Customer With {.Identifier = 2, .Name = "BBBB"})
            MyCustomerList.Add(New Customer With {.Identifier = 3, .Name = "CCCC"})
            bsCustomers.DataSource = MyCustomerList
            DataGridView1.DataSource = bsCustomers
        End Sub
        Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
            Dim sb As New System.Text.StringBuilder
            Dim dt =
                (
                    From T In CType(bsCustomers.DataSource, List(Of Customer))
                    Select New With {.Identifier = T.Identifier, .Name = T.Name}
                ).ToDataTable
            dt.TableName = "Customers"
            DataSet1.Tables.Add(dt)
            For Each row As DataRow In DataSet1.Tables("Customers").Rows
                sb.AppendLine(
                    String.Format("[{0}] [{1}]",
                                  row("Identifier").ToString,
                                  row("Name").ToString)
                )
            Next
            MessageBox.Show(sb.ToString)
        End Sub
    End Class
    Public Class Customer
        Public Property Identifier As Integer
        Public Property Name As String
        Public Sub New()
        End Sub
    End Class

    Code module (this code must be in a code module)

        <System.Diagnostics.DebuggerStepThrough()> _
        <System.Runtime.CompilerServices.Extension()> _
        Public Function ToDataTable(Of T)(ByVal sender As IEnumerable(Of T)) As DataTable
            Dim dt As New DataTable
            Dim FirstRecord = sender.First ' used to create column definition for the table
            For Each pi In FirstRecord.GetType.GetProperties
                dt.Columns.Add(pi.Name, pi.GetValue(FirstRecord, Nothing).GetType)
            Next
            ' Populate the table with data
            For Each result In sender
                Dim nr = dt.NewRow
                For Each pi In result.GetType.GetProperties
                    nr(pi.Name) = pi.GetValue(result, Nothing)
                Next
                dt.Rows.Add(nr)
            Next
            Return dt
        End Function


    KSG

    Thursday, July 05, 2012 3:48 AM
  • Excellent !
    Wednesday, October 24, 2012 4:13 PM