Link to home
Start Free TrialLog in
Avatar of printmedia
printmedia

asked on

How to dynamically populate a datagridview control in vb.net in visual studio 2010

Hi all.

I want to populate a datagridview control based on the value entered in one of my windows form's textbox. So I created a Leave event for the textbox:

    Private Sub txtMasterItemNo_Leave(sender As System.Object, e As System.EventArgs) Handles txtMasterItemNo.Leave
        DataGridView2.DataSource = GetDataTable()

    End Sub

Open in new window


It calls the GetDataTable() function which is where I'm going to grab the data to populate the datagrid.

Private Function GetDataTable() As DataTable
        '
        ' This Function needs to build the data table.
        '
        Dim con As New SqlConnection
        Dim cmd As New SqlCommand
       

        con.ConnectionString = "Data Source=myserver;Initial Catalog=mydb;Integrated Security=True"

        con.Open()

        cmd.Connection = con

        'cmd.CommandText = "INSERT INTO ItemQuote( MasterItemNumber, Description, SLXID, QuoteDate, UnitCost, QuotedCost, Notes) VALUES ('" & txtMasterItemNo.Text & "', '" & txtDescription.Text & "', '" & txtSalesLogixID.Text & "', '" & txtQuoteDate.Text & "', " & txtUnitCost.Text & ", " & txtQuotedCost.Text & ", '" & NotevalueToPutInDatabase & "')"
        cmd.CommandText = "SELECT  MasterItemNumber, Description, SLXID, QuoteDate, UnitCost, QuotedCost, Notes FROM ItemQuote WHERE MasterItemNumber = @MasterItemNo"

        cmd.Parameters.AddWithValue("@MasterItemNo", txtMasterItemNo.Text)

        cmd.ExecuteNonQuery()

        Return New DataTable()

        con.Close()
    End Function

Open in new window


But now I'm stuck, how do I create the column headers and bring in the data?

I simply dragged and dropped the DataGridView control onto my windows form and did not select a data source because the data would be based on what is entered in the textbox.

Thank you in advance!
SOLUTION
Avatar of mankowitz
mankowitz
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Let me know if you need help with the connectionstring.
Avatar of printmedia
printmedia

ASKER

Thank you both!

I used both your suggestions and adjusted mine a bit, and it works.
Super :)
I'll post another question shortly because now I want to join my table with another table that resides on a different server and database. Thanks again!