哪种方法是将选定值添加到数据网格中的快速且好的方法

时间:2014-06-05 11:06:51

标签: c# vb.net datagrid

例如,使用以下控件的形式

  • 组合框(cboProducts
  • 文本框(txtQty
  • trueDBGrid(uisng Component One Control)(grdSale

所以, cboProducts正在填充Product_name,Product_Id from Products表, 选择产品(cboProducts)后,下一步就是输入数量(txtQty) 在输入数量后,网格应填充上面输入的项目。

我的计划

将输入的产品数量添加到Datatbale,然后将Datatable添加到我的grdSale

我认为还有另外一种好的方法,我希望得到好的答案

谢谢

3 个答案:

答案 0 :(得分:0)

我倾向于使用这样的东西, 这假定列已定义

    grdSale.Rows.Clear()

    For Each item As myObject In MyObjects

        Dim row As New DataGridViewRow
        row.CreateCells(grdSale)

        row.Cells(0).Value = item.PKId
        row.Cells(1).Value = item.Product_Desc
        row.Cells(2).Value = item.Quantity
        row.Cells(3).Value = item.Price

        item.Rows.Add(row)
    Next

答案 1 :(得分:0)

GridView使用数据源。在您的情况下,它使用数据表作为其来源。 (我是一个c#开发人员,所以语法可能有点偏离)

Dim dt As New System.Data.DataTable
dt = GetDataFromDB()

gridView.DataSource = dt

成功为控件创建事件后,您应该只在数据表中添加新行,并且更改将在网格中显示。

Sub AddRow(byval productID as Integer, byval productName as string, byval qty as Integer)
  dim row as System.Data.DataRow
  row = dt.NewRow()  'this gets a fresh row from the datatable. Since you already have the datatable defined, the for will have the appropriate columns for your data

  row("productID") = productID
  row("productName") = productName
  row("qry") = qry

  dt.Rows.Add(row) ' at this line you add the new row to the datatable which is "viewed" by a grid and which in turn shows the new information inside itself.

End Sub

答案 2 :(得分:0)

这个怎么样?

Private Sub cboProducts_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles cboProducts.KeyDown
    If e.KeyCode = Keys.Enter Then
        Dim pdt, pdtid As String
        Dim i As Integer
        pdt = cboProducts.Columns(0).Text
        pdtid = cboProducts.Columns(1).Text.ToString
        grdSale.SetDataBinding()
        If grdSale.Rows.Count = 0 Then
            i = 0
        Else
            i = i + grdSale.Rows.Count
        End If
        grdSale.AddRows(1)
        grdSale(i, 0) = pdt
        grdSale(i, 1) = pdtid
    End If
End Sub