Dynamically change the Data Source at runtime? RRS feed

  • Question

  • Hi,


    Is it possible to dynamically change the data source of a datagridview at runtime?


    For example, the user could choose the data source (table to be displayed) from a menu and the datagridview would display this data source dynamically.


    Any help would be much appreciated.




    Tuesday, May 15, 2007 8:48 AM


  • Hi,here is a sample code use combobox to select the datatable of the datagridview.Hope it helps.

    Imports System.Data.SqlClient

    Public Class Form1

        Private dt As New DataTable

        Private Sub Form1_Load_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

            'Dim dt As New DataTable

            dt.Columns.Add("c1", GetType(System.String))

            dt.Columns.Add("c2", GetType(System.String))

            dt.Rows.Add("link1", "Select * From Employees")

            dt.Rows.Add("link2", "Select * From Products")

            Me.ComboBox1.DataSource = dt

            Me.ComboBox1.DisplayMember = "c1"

            Me.ComboBox1.ValueMember = "c1"

        End Sub

        Private Shared Function GetData(ByVal sqlCommand As String) _

        As DataTable

            Dim connectionString As String = _

                "Integrated Security=SSPI;Persist Security Info=False;" _

                & "Initial Catalog=Northwind;Data Source=localhost"

            Dim northwindConnection As SqlConnection = _

                New SqlConnection(connectionString)

            Dim command As New SqlCommand(sqlCommand, northwindConnection)

            Dim adapter As SqlDataAdapter = New SqlDataAdapter()

            adapter.SelectCommand = command


            Dim table As New DataTable

            table.Locale = System.Globalization.CultureInfo.InvariantCulture


            Return table

        End Function

        Private Sub ComboBox1_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles ComboBox1.SelectedIndexChanged

            Dim dt2 As New DataTable

            Dim row1 As DataRow

            row1 = dt.Rows(Me.ComboBox1.SelectedIndex)

            dt2 = GetData(row1.Item(1).ToString)

            Me.DataGridView1.DataSource = dt2

        End Sub

    End Class



    Thursday, May 17, 2007 7:50 AM