0

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
1
  • Don't allow AutoGenerateColumns in your DataGrid Commented Apr 16, 2015 at 12:15

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.