How can I sort the dropdowns in asp.net?

I have a drop down in asp.net that I added some things from the database. In addition, at the end I added some things manually. Now I need to sort these items in a quick and easy way. The drop-down selected value is equal to a number.

Is an object reference useful for my problem? If your answer is yes, please describe.

+4
source share
5 answers

You can create a small utility method like this to sort DropDownList items.

public static void SortListControl(ListControl control, bool isAscending)
{
    List<ListItem> collection;

    if (isAscending)
        collection = control.Items.Cast<ListItem>()
            .Select(x => x)
            .OrderBy(x => x.Text)
            .ToList();
    else
        collection = control.Items.Cast<ListItem>()
            .Select(x => x)
            .OrderByDescending(x => x.Text)
            .ToList();

    control.Items.Clear();

    foreach (ListItem item in collection)
        control.Items.Add(item);
}

Using

protected void Page_Load(object sender, EventArgs e)
{
    for (int i = 0; i < 10; i++)
        DropDownList1.Items.Add(new ListItem(i.ToString(), i.ToString()));

    // Sort the DropDownList Items by descending
    SortListControl(MyDropDownList, false);
}
+4
source
+1

:

        SortedList<int, string> mySortedList = new SortedList<int, string>();
        mySortedList.Add(1, "Hi");
        mySortedList.Add(2, "Hello");
        mySortedList.Add(3, "German");

        dropDownList1.DataTextField = "Value";
        dropDownList1.DataValueField = "Key";
        dropDownList1.DataSource = mySortedList;
        dropDownList1.DataBind();
+1

. , dataview dataview . , dataview.

1. , dataadapter

:

I) :

SqlConnection con=new SqlConnection("Data Source=servername;Database=dbname;Integrated Security=true"); //if windows authentication 
(or) 
SqlConnection con=new SqlConnection("Data Source=servername;Database=dbname;user id=xxx;pwd=xxx"); //if sql authentication 

II) :

SqlDataAdapter sda=new SqlDataAdapter("query",con);

2. DataSet :

DataSet ds=new DataSet();
sda.fill(ds);// filling sda data into dataset using fill method of adapter class

Step 3: Check the dataset is not empty or not. If not empty, create a DataView object and fill it with a sorted option and a combobox:

if(ds.Tables[0].rows.count>0)
{
    DataView dv=new DataView();
    dv.Table=ds.Tables[0]; // filling dataview with dataset
    dv.sort="columnname";
    DropDownList1.DataSource=dv;
    DropDownList1.DataTextField="columnname";
    DropDownList1.DataBind();
    DropDownList1.Items.Insert(0,"select");
}
+1
source

You can configure it as a SortedList, and then just call the list.Sort () method.

You must set the list as a data source and use the key / value fields as DataTextField and DataValueField.

fooobar.com/questions/1517513 / ...

0
source

All Articles