【问题标题】:VB.Net Datagridview to DatatableVB.Net Datagridview 到数据表
【发布时间】:2018-07-24 12:53:04
【问题描述】:

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

基本上,我想要的是(一个伪代码)

datatable = datagridview.datasource


我试过这个,但失败了:

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


和这个,

Dim dt As New DataTable(dgvCarAccidentInjury.DataSource)


我又失败了。 我在c#专栏上看到了这个,但我不知道如何将其转换为vb.net,也许这是解决方案但我不知道VB中的语法。

DataTable data = (DataTable)(dgvMyMembers.DataSource);

我可以通过手动循环来做到这一点,但是有没有像在 C# 上那样的简单方法?


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

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

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

编辑

这个问题的解决方案是这样,通过手动循环。

    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

其他解决方案:

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

【问题讨论】:

  • 你能告诉我们你是如何设置数据源的吗?
  • 我已经编辑过了.. 嗯
  • 是的,问题就在这里。您没有要从 DataGridView 中拉出的 DataTable。
  • 如果您手动创建 datagridview 的行。然后可能更容易将手动创建一个数据表使用相同的数据,将其分配给 datagridvie.datasource 然后使用您的数据表...

标签: vb.net datagridview


【解决方案1】:

你的问题不是选角:

 dt = TryCast(dgvMyMembers.DataSource, DataTable)

但是您的 DataSource 不是 DataTable 而是 字符串数组

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

因此,请确保您的 DataGridView 已正确连接到 DataTable source FIRST,例如:

dgvMyMembers.DataSource = dtSourceHere

可能是你的Form_Load()

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

 dgvMyMembers.DataSource = dtSourceHere

End Sub

如果要将字符串添加到 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")

然后将其设为您的DataGridViewDataSource

    dgvMyMembers.DataSource = dt

您可以稍后在您想要的 TryCast() 上做:

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

【讨论】:

  • 是的,我没看到..lol。我在我的电脑上试过了,它可以工作。可能他还缺少其他东西。谢谢@DonA
  • 我尝试使用 msgbox(dt.rows.count) 进行检查,但它显示“对象引用未设置为对象的实例。”
  • @Codemunkeee:我认为您的 DataSource 尚未正确设置,这就是错误的原因。请参阅我的更新答案。
  • 嗯。我认为这与数据源有关?我用这个 dgvCarAccidentInjury.Rows.Add(New String() {"a", "a", "a", "a"}) 手动将数据插入到数据表中
【解决方案2】:
 Dim DtGrid As DataTable
 DtGrid = CType(dgrd_WWWH.DataSource, DataTable).Copy()

【讨论】:

  • “对象引用未设置为对象的实例。”我尝试使用 MsgBox(DtGrid.Rows(0).Item(0)) 检查 DtGrid 中的值
  • 我认为你的数据源是空的设置断点然后你检查
  • 我也有类似的情况。在尝试您的建议时,我得到 `System.InvalidCastException: Unable to cast object of type 'System.Windows.Forms.BindingSource' to type 'Microsoft.Office.Interop.Excel.DataTable'。
【解决方案3】:

您是否尝试克隆表?如果将DataSource 设置为DataTable,则克隆原始文件。如果您有差异 DataSource - 将无法转换 DataSource

DataTable.Clone

Dim dt As DataTable = originalDt.Clone()

【讨论】:

  • 它说“对象变量或未设置块变量。”将 dt 作为新数据表 dt = dgvCarAccidentInjury.DataSource.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】:

我试过这个方法,效果很好。

                            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                        

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

我希望那是习惯

【讨论】:

    猜你喜欢
    • 2023-03-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-19
    • 1970-01-01
    • 2017-08-19
    • 2012-07-07
    • 2017-02-07
    相关资源
    最近更新 更多