0

I want to sort my listbox using combobox, the combobox will include A-Z and Z-A , so how can I do it and let it work ?

some of my code for the listbox ,lst_OrderName is the one i want to sort.

private void AllorderBySearch()
        {



            using (connection = new SqlConnection(connectionString))
            using (SqlDataAdapter adapter = new SqlDataAdapter("select* from  Tbl_order WHERE CustomerNo = '" + txt_CustomerNo.Text + "' And OrderName LIKE '%" + txt_OrderNo.Text + "%' AND OrderName LIKE '%" + txt_OrderNo.Text + "%' AND OrderName LIKE '%" + txt_OrderNo.Text + "%' AND Date between '" + dateTimePicker1.Text + " 00:00:00.000' AND '" + dateTimePicker1.Text + " 23:59:59.999'; ", connection))
            {


                DataTable Tbl_order = new DataTable();
                connection.Open(); //opens the connection
                adapter.Fill(Tbl_order);
                connection.Close(); //Closes the connection

                lst_CustomerNo.DataSource = Tbl_order; //assigns a datasource
                lst_CustomerNo.DisplayMember = "CustomerNo"; //assigns display
                lst_CustomerNo.ValueMember = "CustomerNo";

                lst_OrderName.DataSource = Tbl_order;
                lst_OrderName.DisplayMember = "OrderName";
                lst_OrderName.ValueMember = "OrderName";

                lst_Quantity.DataSource = Tbl_order;
                lst_Quantity.DisplayMember = "Quantity";
                lst_Quantity.ValueMember = "Quantity";

                lst_Price.DataSource = Tbl_order;
                lst_Price.DisplayMember = "Price";
                lst_Price.ValueMember = "Price";

                lst_datetime.DataSource = Tbl_order;
                lst_datetime.DisplayMember = "Date";
                lst_datetime.ValueMember = "Date";

            }
        }

I created combobox but i didn't do anything in it yet cuse I dunno how to make it by the way i want . could you help me plz?

Max Saeed
  • 13
  • 2
  • 9
  • your answer is in link [Sort Combobox](https://stackoverflow.com/questions/17080830/c-sharp-is-it-possible-to-arrange-combobox-items-from-a-to-z) – p.Monadi Oct 08 '17 at 08:16
  • thanks but what i want to sort is the listbox ^^ , this isn't the answer !? – Max Saeed Oct 08 '17 at 08:20

2 Answers2

0

you must use a temp object for sorting like bubble sort

p.Monadi
  • 1
  • 2
  • 6
0

As you are using a DataTable as the data source, the following should work:

private void cmbSort_SelectedIndexChanged(object sender, EventArgs e)
{
    DataTable dt = lst_CustomerNo.DataSource as DataTable;
    if(cmbSort.SelectedItem == "A-Z")
        dt.DefaultView.Sort = "OrderName ASC";
    else
        dt.DefaultView.Sort = "OrderName DESC";
}

Attach the above event to your combobox SelectedIndexChanged action..