VB.Net Datagridview to Datatable

datagridview, vb.net

Solution

Your problem is not the casting:

 dt = TryCast(dgvMyMembers.DataSource, DataTable)

But your `DataSource` is NOT a `DataTable` but an array of String:

dgvCarAccidentInjury.Rows.Add(New String() {"test1", "test2", "test3", "test4"})

So, make sure that your `DataGridView` was properly connected a `DataTable source` FIRST, like:

dgvMyMembers.DataSource = dtSourceHere

Probably do it your `Form_Load()`

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

 dgvMyMembers.DataSource = dtSourceHere

End Sub

If you want to add your string to your DataGridView, you are better off creating the DataTable add those strings, like:

    Dim dt As New DataTable
    dt.Columns.Add("Names", GetType(String))

    dt.Rows.Add("test1")
    dt.Rows.Add("test2")
    dt.Rows.Add("test3")
    dt.Rows.Add("test4")

Then make it as the `DataSource` of your `DataGridView`:

    dgvMyMembers.DataSource = dt

You could do then later on the `TryCast()` that you desired:

    Dim dtNew As New DataTable
    dtNew = TryCast(dgvMyMembers.DataSource, DataTable)

Problem

I wanted to create a datatable based from a 5 column datatable. Also, I would like to remove the last column (it is an image column). Basically, what I wanted to have is ( a pseudocode ) ``` datatable = datagridview.datasource ``` I have tried this, but failed: ``` Dim dt As New DataTable dt = TryCast(dgvCarAccidentInjury.DataSource, DataTable) ``` And this, ``` Dim dt As New DataTable(dgvCarAccidentInjury.DataSource) ``` Again I failed. I saw this on the c# column but I don't know how to convert it to vb.net, maybe this is the solution but I don't know the syntax in VB. ``` DataTable data = (DataTable)(dgvMyMembers.DataSource); ``` I can do it by manually looping but is there an easy way like how it is on C#? EDIT I have set my datagridview's data manually by doing this line of code, ``` dgvCarAccidentInjury.Rows.Add(New String() {"test1", "test2", "test3", "test4"}) ``` Also, there is a 5th column (an image column), actually it is empty. Sorry I have missed this important point out. EDIT the solution for this problem is this, by manually looping. ``` Dim dt As New DataTable Dim r As DataRow dt.Columns.Add("a", Type.GetType("System.String")) dt.Columns.Add("b", Type.GetType("System.String")) dt.Columns.Add("c", Type.GetType("System.String")) dt.Columns.Add("d", Type.GetType("System.String")) For i = 0 To dgvCarAccidentInjury.Rows.Count - 1 r = dt.NewRow r("a") = dgvCarAccidentInjury.Item(0, i).Value.ToString r("b") = dgvCarAccidentInjury.Item(1, i).Value.ToString r("c") = dgvCarAccidentInjury.Item(2, i).Value.ToString r("d") = dgvCarAccidentInjury.Item(3, i).Value.ToString dt.Rows.Add(r) Next ``` Other solutions: ``` Dim dt As New DataTable dt = TryCast(yourdatagridview.DataSource, DataTable) ```

Original source