0

I have a drop down list for cities, and I have cities in my database that I want to populate to a drop down list.

On the Page load made an sql connection

 Dim s As String = "Connection String"
 sqlconn = New SqlConnection(s) 

Now on the drop down load I have a query which is working fine. How to add results from the database query to the drop down?

   Protected Sub Citydropdown_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Citydropdown.Load

        sqlCmd = New SqlCommand("select City from usrRegister_aunthentication", sqlconn)
        If sqlconn.State = Data.ConnectionState.Closed Then
            sqlconn.Open()
        End If
        Dim i As String = sqlCmd.ExecuteReader()

        If sqlconn.State = Data.ConnectionState.Open Then
            sqlconn.Close()
        End If
    End Sub

Also, sometimes the same city is repeated. How do I only show each city once?

1
  • Pro tip: you'll get better answers if you put more work into your question. See the edit for what something that's much easier for those of who answer to use. Also, I hope you pay a lot more attention to the details of your code than you did to your question here. Commented Dec 26, 2011 at 17:30

2 Answers 2

4

Do not use ExecuteNonQuery to fetch the result (rows). Use ExecuteReader to obtains the reader instance.

Dim dataReader as SqlDataReader 
dataReader = sqlCmd.ExecuteReader()
While dataReader.Read
  ' Write code to insert an Item into dropdownlist
  DropDownItem1.Items.Add(dataReader("City").ToString())
End While
dataReader.Close()
Sign up to request clarification or add additional context in comments.

9 Comments

that i have edited but what code i have to wrtie so as to fill data in the drop -down , which code should e written in while loop?
and more ova when i use ExecuteReader it says SqldataReader can not be convertedt to string
can i ask u 1 more query ? in the same ques above ?
Do you want to fetch distinct city? SELECT DISTINCT CITY from usrRegister_aunthentication
You should post a question with complete problem description.
|
0

You could also try this. It is a line or two less.

Using dr = sqlCmd.ExecuteReader()
While dr.Read
     ' Write code to insert an Item into dropdownlist
     DropDownItem1.Items.Add(dr("City").ToString())
End While
End Using

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.