VB.Net Datagridview to Datatable

一曲冷凌霜 提交于 2021-02-19 02:51:06

问题


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)

回答1:


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)



回答2:


 Dim DtGrid As DataTable
 DtGrid = CType(dgrd_WWWH.DataSource, DataTable).Copy()



回答3:


Did you try cloning the table? If you set the DataSource with a DataTable you clone the original. If you have a diff DataSource - it will not work converting the DataSource.

DataTable.Clone

Dim dt As DataTable = originalDt.Clone()



回答4:


--MENU--
Dim login As New LoginClass
login.ShowDialog()

--CONEXION--
Private conec As SqlConnection
Dim stringCon As String = "Data Source= ;Initial Catalog=;Persist Security Info=True;User ID=;Password="
Public ReadOnly Property prConec() As Object
    Get
        Return conec
    End Get
End Property
Public Sub Conectar()
    Try
        conec = New SqlConnection(stringCon)
        If conec.State <> ConnectionState.Open Then
            conec.Open()
        End If
    Catch ex As Exception
        MessageBox.Show(ex.Message)
    End Try
End Sub

--BUSCAR--
funciones.Conectar()
Dim coman As New SqlCommand("sp_cliente", funciones.prConec)
Dim dt As New DataTable
coman.CommandType = CommandType.StoredProcedure
coman.Parameters.Add("@i_operacion", SqlDbType.Char, 1, ParameterDirection.Input).Value = "B"
dt.Load(coman.ExecuteReader())
grdClientes.DataSource = dt

--INSERTAR--
funciones.Conectar()
Dim coman As New SqlCommand("sp_articulo", funciones.prConec)
coman.CommandType = CommandType.StoredProcedure
coman.Parameters.Add("@i_operacion", SqlDbType.Char, 1, ParameterDirection.Input).Value = "I"
coman.ExecuteNonQuery()
Buscar()
Limpiar()

--COMBO--
Dim dt As New DataTable
dt.Columns.Add("Codigo")
dt.Columns.Add("Descripcion")
Dim dr1 As DataRow = dt.NewRow
dr1.Item("Codigo") = "A"
dr1.Item("Descripcion") = "Activo"
dt.Rows.Add(dr1)
Dim dr2 As DataRow = dt.NewRow
dr2.Item("Codigo") = "I"
dr2.Item("Descripcion") = "Inactivo"
dt.Rows.Add(dr2)
cmbEstado.DataSource = dt
cmbEstado.ValueMember = "Codigo"
cmbEstado.DisplayMember = "Descripcion"

--GRIDVIEW--
--1--
Dim grdFila As DataGridViewRow = grdClientes.CurrentRow
txtCedula.Text = grdFila.Cells(0).Value
--2--
If DataGridProductos.CurrentCell.ColumnIndex = 0 Then
    Dim FLstArticulos As New FLstArticulos
    FLstArticulos.ShowDialog()
    DataGridProductos.CurrentRow.Cells(0).Value = FLstArticulos.PrIdArticulo
End If

--GRIDVIEW.CELLENDEDIT--
If DataGridProductos.CurrentCell.ColumnIndex = 3 Then
    Dim precio As New Double
    Dim cantidad As New Double
    precio = CDbl(grdRow.Cells(2).Value)
    cantidad = CDbl(grdRow.Cells(3).Value)
    DataGridProductos.CurrentRow.Cells(4).Value = PLTotalFilaItem(cantidad, precio)
    PLCargaTotales()
End If

Sub PLCargaTotales()
    Dim subTotal As Double
    Dim iva As Double
    For Each grd As DataGridViewRow In DataGridProductos.Rows
        If Not String.IsNullOrEmpty(grd.Cells(4).Value) Then
            subTotal = subTotal + CDbl(grd.Cells(4).Value)
        End If
    Next grd
    txtSubtotal.Text = subTotal.ToString
    iva = Decimal.Round(subTotal * 0.12)
    txtIva.Text = iva.ToString
    txtTotalPagar.Text = (subTotal + iva).ToString
End Sub



回答5:


I've tried this method and it works properly.

                            Dim dt As New DataTable
                            Dim dc As DataColumn = New DataColumn("MOBILENUMBER")
                            dc.DataType = System.Type.GetType("System.String")
                            dc.MaxLength = 15
                            dt.Columns.Add(dc)
                            For n As Integer = 0 To dgvMobiles.Rows.Count - 2
                                dtr = dt.NewRow()
                                dtr.Item("MOBILENUMBER") = dgvMobiles.Rows(n).Cells(0).Value
                                dt.Rows.Add(dtr)
                            Next                        

Where dgbMobiles is the datagridview which i can enter my contacts mobile numbers.

I hope that is usu



来源:https://stackoverflow.com/questions/20209241/vb-net-datagridview-to-datatable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!