Sorting Of DropDownList Alphabetically Using C#

In this post,we will learn how to sort DropDownList items alphabetically in c# If the data are in a DataTable.

DropDownlist Looks Like –


Code behind(c#) –

using System.Data;
using System.Web.UI.WebControls 

 DataTable excelColumnNames = new DataTable();                                                                             
                excelColumnNames.Columns.Add("Column Name", typeof(string));                                             //Add the column in new datatable
                excelColumnNames.Columns.Add("Id", typeof(string));
                int counter = 0;
                List<string> excelCols = new List<string>();
                foreach (DataColumn col in dataTable.Columns)
                    DataRow row = excelColumnNames.NewRow();
                    string ColName = "";
                    row["Column Name"] = col.ColumnName;
                    row["Id"] = counter++;
                    excelColumnNames.Rows.Add(row);                                                                         //Add the row in new datatable
                DataView dataview = excelColumnNames.DefaultView;
                dataview.Sort = "Column Name";                                                                              //Do the sorting of columnname                                                         
                excelColumnNames = dataview.ToTable();                                                                //Get the sorted colname in datatable                     
                DropDownList.DataSource = excelColumnNames;                                                                  //Pass it to dropdownlist          

After Sorting (Output) –

Submit a Comment

Your email address will not be published. Required fields are marked *


Select Categories