Getdata VB.NET function

Asked

Viewed 60 times

0

I’m trying to create a function to update Datagridview. I added the following code but gave an error "Unable to clear the list"

Code:

    Private Sub GetData()
    Try
        con = New SqlConnection(cs)
        con.Open()
        cmd = New SqlCommand("SELECT nome, matricula, marca, [Licenca-emissao], [licenca-expira] from Clientes order by Nome", con)
        rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection)
        dgw.Rows.Clear()
        While (rdr.Read() = True)
            dgw.Rows.Add(rdr(0), rdr(1))
        End While
        con.Close()
    Catch ex As Exception
        MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
    End Try
End Sub
  • you are setting your dgw’s Datasource somewhere before?

  • @Brunopiovan did not realize the "SETANDO"

  • vc is assigning the previously Datasource property somewhere else?

  • @Brunopiovan Yes, in various Forms

  • That’s why you can’t clean the Rows because there is an assigned datasource, you have to clean the "Rows" from your datasource. I will respond with a recommendation.

  • @Brunopiovan am an amateur developer yet, could make it a little easier. And I notice more programming in English

  • ok! check These out, Might help http://stackoverflow.com/questions/6184402/how-can-i-clear-rows-in-datagridview-with-c http://stackoverflow.com/questions/18151641/filling-a-datagridview-from-sqlreader

  • Thanks, but this is C#, I’ve never touched C# @Brunopiovan

  • I tried using the function datatable.Clear dataGridView.Refresh More didn’t work

Show 4 more comments

1 answer

1


Try this:

Private Sub GetData()
    Try
        con = New SqlConnection(cs)
        con.Open()
        cmd = New SqlCommand("SELECT nome, matricula, marca, [Licenca-emissao], [licenca-expira] from Clientes order by Nome", con)
        rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection)

        Dim dt = New DataTable()
        dt.Load(rdr)
        dgw.AutoGenerateColumns = True
        dgw.DataSource = dt
        dgw.Refresh()

        con.Close()
    Catch ex As Exception
        MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
    End Try
End Sub

As I said in the commentary, you cannot clear the lines because you yourself said you are assigning a Datasource earlier, so you need to touch it, and not the lines of your Datagridview.

  • Thank you, I’ll check it out, then I’ll say something :)

  • Very grateful @Brunopiovan worked :) I spent nights and nights trying to solve this...

  • I am glad to have helped! If you can accept this answer as the correct one then. =)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.