title: how to build dynamic query to sql database in vb.net
body: <p>I would like to fill combobox by using dynamic query. To do this, it was created external class called <strong>sqlcnn</strong>. This class defines connection to sql databases and it works properly. Here below code:</p>
  
  <pre><code>Imports System.Data.SqlClient
  </code></pre>
  
  <p>Public Class sqlcnn</p>
  
  <pre><code>Public cnn As New SqlConnection("Data Source=(local)\sqlexpress...)
  Public Command As SqlCommand
  Public txt() As String
  Public i As Integer
  
  Public Sub execute_command(ByVal query As String)
  
      Try
          cnn.Open()
  
          Command = New SqlCommand(query, cnn)
  
          Dim readerr = Command.ExecuteReader
  
          ReDim txt(readerr.FieldCount - 1)
  
          While readerr.Read
  
  
              For i = 0 To readerr.FieldCount - 1
                  txt(i) = readerr.Item(i)
  
              Next i
  
  
          End While
  
          MsgBox("Connection Open ! ")
          cnn.Close()
      Catch ex As Exception
          MsgBox("Can not open connection ! ")
      End Try
  
  
  End Sub
  </code></pre>
  
  <p>End Class</p>
  
  <p>If I modify the code above by adding into for loop one line more:</p>
  
  <pre><code> For i = 0 To readerr.FieldCount - 1
                  txt(i) = readerr.Item(i)
                  ComboBox1.Items.Add(txt(i))
  
              Next i
  </code></pre>
  
  <p>I can fill immediately the combobox, without any problem.</p>
  
  <p>The problem is, when I try to fill combobox from main class called Form1.
  This class defines one combobox1 and one button. Here below the code:</p>
  
  <pre><code>Imports System.Data.SqlClient
  </code></pre>
  
  <p>Public Class Form1</p>
  
  <pre><code>Private Sql As New sqlcnn
  Dim i As Integer
  
  Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
  
      Sql.execute_command("select Car from shopcars")
  
      For i = 0 To (Sqlpol.txt.Length - 1)
  
          ComboBox1.Items.Add(Sqlpol.txt(i))
  
      Next i
  
  
  End Sub
  </code></pre>
  
  <p>End class</p>
  
  <p>The result is that, inside the combobox we can see only last item of my database. Completely, I don't have idea how to build properly for loop.
  I'm grateful for the help. </p>
  
  <p>thanks! </p>