Abd Domingos
Abd Domingos

Reputation: 55

Clear datagridview and add new values vb.net mysql

I have a datagridview that fills data using a join table, and I want to every time that a specific data (Box No.) changes from the database automatically clear the data and add new (not to delete just hide and show new data)

Ex: When the Box No. changes from 1 to 2, hide data from Box 1 and only show data from Box 2. The datagridview

The Conn and Join:

Dim conn As New deepconnection()
Dim adapter As New MySqlDataAdapter()
Dim table As New DataTable()
Dim ds, ds1 As New DataSet
Dim Joinloin As New MySqlCommand("SELECT boxno, specie, netweight, projectcode, loin FROM loins, boxing WHERE loins.code = boxing.loin ORDER BY loincode", conn.getConnection)

Fill Data Code:

conn.openOcean()
        adapter = New MySqlDataAdapter(Joinloin)
        table.Rows.Clear()
        adapter.Fill(table)
        If Not table Is Nothing AndAlso table.Rows.Count > 0 Then
            DataGridView1.AutoGenerateColumns = False
            DataGridView1.DataSource = table
            DataGridView1.Columns(0).DataPropertyName = "boxno"
            DataGridView1.Columns(1).DataPropertyName = "specie"
            DataGridView1.Columns(2).DataPropertyName = "netweight"
            DataGridView1.Columns(3).DataPropertyName = "loin"
            DataGridView1.Columns(4).DataPropertyName = "projectcode"
        End If

Upvotes: 1

Views: 211

Answers (1)

J. Rockwood
J. Rockwood

Reputation: 118

HardCode is exactly correct on all their points.

The SELECT statement should be cleaned up using a JOIN like so:

SELECT boxno, specie, netweight, projectcode, loin 
FROM loins
    JOIN boxing 
        ON LOINS.CODE = BOXING.CODE
ORDER BY loincode

USING statements are very nice and helpful because they automatically dispose the USED objects so you don't have to worry about manually doing so yourself. An example one I share is how you can declare multiple sql objects in one using statement (as they generally are used and disposed together)

Dim sqlResult As DataTable

Using cn As New SqlConnection("Your Connection String"),
      cmd As New SqlCommand("Your SQL Statement", cn),
      adapt As New SqlDataAdapter(cmd)

      cn.Open()
      cmd.Parameters.AddWithValue("@Parameter", ValueOfParameter) 'If Used Leave Out If Not
      sqlResult = New DataTable(cmd.CommandText)
      adapt.Fill(sqlResult)
End Using

And the other points as well, but that should get you somewhere.

Upvotes: 1

Related Questions