Lee Song
Lee Song

Reputation: 83

VB.net Loading data to datagridview from Mysql

I have a datagridview and I already put 3 columns in there (via design), but when I run this code, it adds another 3 columns and the data loads in those newly created ones. How can it just load the data from the columns that I made?

EDIT: 1st and 2nd Column is textbox, and 3rd is combobox.

the code is in form load:

    Dim sqlDataAdapter As New MySqlDataAdapter
    Dim dt As New DataTable
    Dim bSource As New BindingSource

    Try
        sqlconn.Open()
        Dim query As String
        query = "SELECT * FROM tbl_subject ORDER BY yearlevel, code"
        sqlcommand = New MySqlCommand(query, sqlconn)
        sqlDataAdapter.SelectCommand = sqlcommand
        sqlDataAdapter.Fill(dt)
        bSource.DataSource = dt
        datagrid_Subject.DataSource = bSource
        sqlDataAdapter.Update(dt)

        sqlconn.Close()
    Catch ex As Exception
        MessageBox.Show(ex.Message)
    Finally
        sqlconn.Dispose()
    End Try

Upvotes: 0

Views: 6738

Answers (2)

W.Hillary
W.Hillary

Reputation: 1

just go to toolbox and drag and drop datagridview, on properties name it something like dgvSubject example using your code above it will look like this;

Dim sqlDataAdapter As New MySqlDataAdapter Dim dt As New DataTable Dim bSource As New BindingSource

Try
    sqlconn.Open()
    Dim query As String
    query = "SELECT * FROM tbl_subject ORDER BY yearlevel, code"
    sqlcommand = New MySqlCommand(query, sqlconn)
    sqlDataAdapter.SelectCommand = sqlcommand
    sqlDataAdapter.Fill(dt)
    bSource.DataSource = dt
    dgvSubject.DataSource = bSource
    sqlDataAdapter.Update(dt)

    sqlconn.Close()
Catch ex As Exception
    MessageBox.Show(ex.Message)
Finally
    sqlconn.Dispose()
End Try

Upvotes: 0

Fabio
Fabio

Reputation: 32445

Columns of DataGridView have property DataPropertyName, set it value to column names from your sql query.
This will show data in predefined columns

And as @Icepickle said in the comments set datagrid_Subject.AutoGenerateColumns = False
This will prevent datagridview to generate columns for all fields used in the SELECT statements of your sql query

Upvotes: 1

Related Questions