VB.Net Datagridview转数据表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20209241/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 17:18:46  来源:igfitidea点击:

VB.Net Datagridview to Datatable

vb.netdatagridview

提问by Codemunkeee

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).

我想根据 5 列数据表创建一个数据表。另外,我想删除最后一列(它是一个图像列)。

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.


我又失败了。我在 c# 专栏上看到了这个,但我不知道如何将其转换为 vb.net,也许这是解决方案,但我不知道 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#?

我可以通过手动循环来完成,但是有没有像 C# 这样的简单方法?



EDITI have set my datagridview's data manually by doing this line of code,

编辑我通过执行这行代码手动设置了我的 datagridview 的数据,

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.

此外,还有第 5 列(图像列),实际上它是空的。对不起,我错过了这个重要的点。

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)

回答by Edper

Your problem is not the casting:

你的问题不是演员:

 dt = TryCast(dgvMyMembers.DataSource, DataTable)

But your DataSourceis NOT a DataTablebut an array of String:

但是,你DataSource是不是一个DataTable而是一个字符串数组

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

So, make sure that your DataGridViewwas properly connected a DataTable sourceFIRST, like:

因此,请确保您DataGridView已正确连接DataTable sourceFIRST,例如:

dgvMyMembers.DataSource = dtSourceHere

Probably do it your Form_Load()

大概做你的 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:

如果要将字符串添加到 DataGridView,最好创建 DataTable 添加这些字符串,例如:

    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 DataSourceof your DataGridView:

然后将其设为DataSource您的DataGridView

    dgvMyMembers.DataSource = dt

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

你可以稍后做TryCast()你想要的:

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

回答by sk2185

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

回答by OneFineDay

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

你试过克隆表吗?如果DataSource使用 a设置,则DataTable克隆原始文件。如果您有差异DataSource- 将无法转换DataSource.

DataTable.Clone

数据表.Clone

Dim dt As DataTable = originalDt.Clone()

回答by Jorge Díaz Sánchez

--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

回答by Hisham Shaaban

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 dgbMobilesis the datagridview which i can enter my contacts mobile numbers.

其中dgbMobiles是 datagridview,我可以输入我的联系人手机号码。

I hope that is usu

我希望那是正常的