清除DataGridView而不会丢失源

时间:2014-01-18 15:50:14

标签: vb.net winforms datagridview

我有一个DataGridView的表单,dataTable的dataSourced。当我在最后插入记录时,按下清除按钮或表格,当我按下保存按钮时,所有字段(文本框,组合框,DGV复选框)都会自动清除。

我通常通过写下来清除文本框和组合框:

textbox1.text = ""
combobox1.text = ""

但是当我用这样清除DGV时:

dgvPurchase.dataSource = nothing
dgvPurchase.Refresh()

或     dgvPurchase.rows.clear()

确实清除了DGV,但是当我添加新条目时,DataGridView和数据都不会出现在DGV中。在Form Load事件中,我有以下代码:

dtField = retrieveFull("ProductBasicInfo")

cmbPurProdID.DisplayMember = "ProdName"
    cmbPurProdID.ValueMember = "ProdID"
    cmbPurProdID.DataSource = dtField


 dtPurchase.Columns.Add("ProdID")
 dtPurchase.Columns.Add("ProdName")
 dtPurchase.Columns.Add("RetailerID")
 dtPurchase.Columns.Add("RetailerName")
 dtPurchase.Columns.Add("UnitPrice")
 dtPurchase.Columns.Add("Qty")
 dtPurchase.Columns.Add("Amount")

 dgvPurchase.DataSource = dtPurchase

请指导我,我的DataSource有什么办法不打扰,或者如果我清除它,那么它也会刷新DataSource。

这是添加按钮代码,它将数据添加到DataGridView

 Try

        For a As Integer = 0 To dtPurchase.Rows.Count - 1
            If dtPurchase.Rows(a).Item("ProdID") = cmbPurProdID.SelectedValue Then
                MessageBox.Show("This product is already enlisted")
                Exit Sub
            End If
        Next


        dRow = dtPurchase.NewRow

        dRow.Item("ProdID") = cmbPurProdID.SelectedValue
        dRow.Item("ProdName") = cmbPurProdID.Text
        dRow.Item("RetailerID") = cmbPurRetailerID.SelectedValue
        dRow.Item("RetailerName") = cmbPurRetailerID.Text
        dRow.Item("UnitPrice") = txtPurUnitPrice.Text.Trim
        dRow.Item("Qty") = txtPurQty.Text.Trim
        dRow.Item("Amount") = txtPurAmount.Text.Trim

       dtPurchase.Rows.Add(dRow)

1 个答案:

答案 0 :(得分:0)

您可以创建新的空DataTable并将其设置为:

C#

DataTable emptyDT = new DataTable();
dgvPurchase.DataSource = emptyDT

vb.Net

Dim emptyDT As New DataTable()
dgvPurchase.DataSource = emptyDT

这对你有用吗?