简体   繁体   English

清除数据绑定datagridview vb.net

[英]Clear Databound datagridview vb.net

I have a datagridview that gets data from the database, it's working fine but then when i close the form and open it again it wont clear the previous content. 我有一个datagridview从数据库中获取数据,它工作正常,但是当我关闭窗体并再次打开它时,它不会清除以前的内容。 It will output the previous selection with the new selection made. 它将输出先前的选择和新的选择。 I have tried this codes: 我已经尝试过以下代码:

    compSpecs.modelDatagridview1.DataSource = Nothing
    compSpecs.modelDatagridview1.Rows.Clear()
    compSpecs.modelDatagridview1.Columns.Clear()

But it still wont clear. 但是它仍然不会清除。 Maybe i'm not doing it right. 也许我做错了。 Please help. 请帮忙。

This is my code: 这是我的代码:

Private Sub load_model2()
    conn = New MySqlConnection
    conn.ConnectionString = "server=127.0.0.1; port=3306; username=root; password=p@ssw0rd; database= atos_db"
    Dim sda As New MySqlDataAdapter
    Dim bsource As New BindingSource
    compSpecs.modelDatagridview2.DataSource = Nothing
    compSpecs.modelDatagridview2.Rows.Clear()
    compSpecs.modelDatagridview2.Columns.Clear()
    Try
        conn.Open()
        Dim query As String
        query = "select * from atos_db.itemdetails_tbl left join atos_db.brand_tbl on itemdetails_tbl.brand_id = brand_tbl.brand_id left join atos_db.item_tbl on brand_tbl.item_id=item_tbl.item_id where item='" & itemCombobox2.Text & "'"
        comm = New MySqlCommand(query, conn)
        sda.SelectCommand = comm
        sda.Fill(dbDataset)
        bsource.DataSource = dbDataset
        compSpecs.modelDatagridview2.DataSource = bsource
        sda.Update(dbDataset)
        conn.Close()
    Catch ex As MySqlException
        MessageBox.Show(ex.Message)
    Finally
        conn.Dispose()
    End Try
End Sub

Firstly, that implies that you're using the same instance of the form each time. 首先,这意味着您每次都使用相同的表单实例。 If you create a new instance of the form each time you want to display it then there can't be anything left over from last time. 如果您每次要显示表单时都创建一个新的表单实例,则上次没有任何剩余。

If you don't want to do that though, there's no use unbinding the grid from the data source if you're only going to rebind it again. 但是,如果您不想这样做,则只重新绑定一次就没有用。 If the data is still in the data source then the grid will just display it again. 如果数据仍在数据源中,则网格将再次显示它。 If you want to get rid of the data then you need to clear the data source. 如果要删除数据,则需要清除数据源。 The grid displays what's in the data source so clear the data source and the grid will be cleared too. 网格显示数据源中的内容,因此清除数据源,网格也将被清除。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM