Quantcast
Channel: Windows Forms Data Controls and Databinding forum
Viewing all articles
Browse latest Browse all 2535

Binding SQL Query Result to DataGridView Dynamically

$
0
0
I am trying to take text from a Rich Text Box and execute that code as an SQL command. Then, the resulting table should be displayed in a DataGridView.

Currently, I have it so the SQL command is working properly, but I can't figure out how to bind the data that I have to the DataGridView, or at least display it.  I don't want to bind the data through Visual Studio's GUI because the SQL query can be performed on any of four tables within my data set.

Here is a screen shot of what I am trying to accomplish.

Here is the code that I have so far.  It performs the connection, executes the command, and prints two columns of the resulting table in the console:

    Private Sub btnExecute_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnExecute.Click
        Try
            Dim connection As New Data.SqlClient.SqlConnection("Data Source=.\SQLEXPRESS;AttachDbFilename=C:\inventory.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True")
            connection.Open()

            Dim input As String = rtbInput.Text
            Dim command As New Data.SqlClient.SqlCommand(input, connection)

            command.ExecuteNonQuery()

            Dim reader As Data.SqlClient.SqlDataReader = command.ExecuteReader()
            Try
                While reader.Read()
                    Console.WriteLine(String.Format("{0}, {1}", _
                        reader(0), reader(1)))
                End While
            Finally
                reader.Close()
            End Try

        Catch ex As InvalidOperationException
            MessageBox.Show(ex.ToString())
        End Try
    End Sub

I have done my best to give as much detail as possible.  Any help would be greatly appreciated!

Viewing all articles
Browse latest Browse all 2535

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>