winforms – How to associate datatable fields with DataGridView columns?

Question:

My problem is the following, I make a query in the database that returns a datatable with a wide variety of fields. The purpose is to display this query in the datagridview, however, displaying only some of the datatable's fields.

I had previous code here, but it just crashed.

I will describe the process:

  • 1st Search the Database and Returns the Filled Datatable
  • 2nd Create columns in the datagridview and associate them to Datatable fields

     With DgvErros .ColumnCount = 2 .AutoGenerateColumns = False .Columns(0).Name = "Codigo_Produto" .Columns(0).DataPropertyName = "Codigo_Produto" .Columns(1).Name = "Descricao" .Columns(1).DataPropertyName = "Descricao" .DataSource = Bs .AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells End With

In my query, I have the field " Codigo_Produto "… but the program raises an error when reaching the part where it gives a name to column 0 of the DataGridView.

Error: "Cannot set ColumnCount property on a data-bounded DataGridView control."

Answer:

This form will cause an error in the next search, so on input it will work after that it will give an error because the columns are already present… so, do the separate configuration routine, from the update routine…

Example:

Private Sub Configurar_GridView()
    With DgvErros
        .ColumnCount = 2
        .AutoGenerateColumns = False
        .Columns(0).Name = "Codigo_Produto"
        .Columns(0).DataPropertyName = "Codigo_Produto"
        .Columns(1).Name = "Descricao"
        .Columns(1).DataPropertyName = "Descricao"
        .AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells
        .AllowUserToAddRows = False
        .AllowUserToDeleteRows = False
        .AllowUserToOrderColumns = False
        .AllowUserToResizeColumns = False
        .AllowUserToResizeRows = False
    End With
End Sub

Private Sub Executar_Pesquisa()
    Dim Bs = New DataTable("Bs")
    Bs.Columns.Add("Codigo_Produto")
    Bs.Columns.Add("Descricao")
    Dim Row = Bs.NewRow()
    Row("Codigo_Produto") = 1
    Row("Descricao") = "Nome 1"

    Bs.Rows.Add(Row)

    'Dim DgvErros = New DataGridView
    With DgvErros
        .DataSource = Bs
    End With
    Panel1.Controls.Add(DgvErros)
End Sub

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    Configurar_GridView()
    Executar_Pesquisa()
End Sub

Private Sub ButIniciar_Click(sender As Object, e As EventArgs) Handles ButIniciar.Click        
    Executar_Pesquisa()
End Sub

Because, the configuration is only 1 time, then you can do the searches and return this DataTable the way you want (with filter for example). The button ButIniciar_Click only performs the method Executar_Pesquisar that it assigns only the datatable (the datatable is that the code is an example).

Scroll to Top
AllEscort