C# .NET - sort the values - Asked By phanindra jagannadula on 10-Nov-11 01:02 AM

hello,
am taking the values from table
 da1 = new SqlDataAdapter("select CATAGORY from CATAGORY", con);
      DataSet p4 = new DataSet();
      p4.Clear();
      da1.Fill(p4, "CATAGORY");

am binding this data to the dropdownlist the values in the dropdown is not in aplhabet now i want to sort the values
in alphabetically.
is there any code for sorting the values.???

thanking you
Kirtan Patel replied to phanindra jagannadula on 10-Nov-11 01:06 AM
use Orderby Clause to do that in query

da1 = new SqlDataAdapter("select CATAGORY from CATAGORY ORDER By [CATAGORY]", con);
DataSet p4 = new DataSet();
p4.Clear();
da1.Fill(p4, "CATAGORY");
Suchit shah replied to phanindra jagannadula on 10-Nov-11 01:13 AM
Check out below sample which help u to achive your task

protected
void Page_Load(object sender, EventArgs e)
    {
      this.DropDownList1.Items.Add("Orange");
      this.DropDownList1.Items.Add("Grapes");
      this.DropDownList1.Items.Add("Apple");
      this.DropDownList1.Items.Add("Mango");
      this.DropDownList1.Items.Add("Lemon");
      this.DropDownList1.Items.Add("Banana");
     
    SortDDL(ref this.DropDownList1);
    }  

private
void SortDDL(ref DropDownList objDDL)
   {
      ArrayList textList = new ArrayList();
      ArrayList valueList = new ArrayList();


      foreach (ListItem li in objDDL.Items)
      {
        textList.Add(li.Text);
      }   

      textList.Sort();


      foreach (object item in textList)
      {
        string value = objDDL.Items.FindByText(item.ToString()).Value;
        valueList.Add(value);
      }
      objDDL.Items.Clear();

    for(int i = 0; i < textList.Count; i++)
      {
        ListItem objItem = new ListItem(textList[i].ToString(), valueList[i].ToString());
        objDDL.Items.Add(objItem);
      }
   }
Suchit shah replied to phanindra jagannadula on 10-Nov-11 01:13 AM
If you get a DataTable with the data, you can create a DataView off of this and then bind the drop down list to that. Your code would look something like...

DataView dvOptions = new DataView(DataTableWithOptions);
dvOptions.Sort = "Description";
 
ddlOptions.DataSource = dvOptions;
ddlOptions.DataTextField = "Description";
ddlOptions.DataValueField = "Id";
ddlOptions.DataBind();

Your text field and value field options are mapped to the appropriate columnns in the data table you are receiving.

phanindra jagannadula replied to Kirtan Patel on 10-Nov-11 01:14 AM
thank u problem solved..
phanindra jagannadula replied to Kirtan Patel on 10-Nov-11 01:14 AM
thank u problem solved..