0

i use this code to fill the search result records in combo pox and it working good ..

    da = New SqlDataAdapter("Select * From MovTable where NameOfMov like '" & AlphaCB.Text & "%'", sqlcon)
    da.Fill(dt0)
    SearchResultCbB1.DataSource = dt0
    SearchResultCbB1.ValueMember = "NameOfMov"

but i need some change to make the combo pox sorting them by Alphabet

thanks

3 Answers3

2

When you attach a ComboBox's datasource to a datatable (dt0) it actually attaches to the .DefaultView DataView of the table. This means you can set the .Sort property of the view to sort the combo:

dt0.DefaultView.Sort = "[NameOfMov] ASC";
SearchResultCbB1.DisplayMember = "NameOfMov" 'this shows in the combo
SearchResultCbB1.ValueMember= "ID" 'you probably want an ID, not the movie name, for this
SearchResultCbB1.DataSource = dt0

You can change this Sort property at any time. For more info on what you can do with it, see the documentation

Please don't write SQL's like you have there; it's a massive security flaw. For more info on why, read http://bobby-tables.com - it will also give advice on how to prevent it, but really you should look at upgrading your knowledge to use Entity Framework or Dapper for your data access and never again, ever concatenate a value into an SQL string

Caius Jard
  • 72,509
  • 5
  • 49
  • 80
0

this is an alternative right answer for my question

da = New SqlDataAdapter("Select * From MovTable where NameOfMov like '" & AlphaCB.Text & "%' order by NameOfMov ", sqlcon)

All I needed was this one addition "order by NameOfMov"

Didn't need all this hassle.

0

Please always use parameters to avoid sql injection and make you your sql query strings easier to write. I had to guess the datatype and size of the parameter. Please check your database for the actual values and adjust the code.

The user interface is updated after the database objects are closed and disposed with the Using...End Using block.

Private Sub OPCode()
    Dim dt0 As New DataTable
    Using sqlcon As New SqlConnection("Your connection string"),
            da As New SqlDataAdapter("Select * From MovTable where NameOfMov like @Name Order By NameOfMov;", sqlcon)
        da.SelectCommand.Parameters.Add("@Name", SqlDbType.NVarChar, 400).Value = AlphaCB.Text & "%"
        da.Fill(dt0)
    End Using
    SearchResultCbB1.DataSource = dt0
    SearchResultCbB1.DisplayMember = "NameOfMov"
    SearchResultCbB1.ValueMember = "MovieID" 'The Primary Key field in you Database
End Sub
Mary
  • 14,926
  • 3
  • 18
  • 27