[英]how can i sort drop down items in asp.net?
我在asp.net中有一个下拉列表,我从数据库中添加了一些东西。 最后我还手动添加了一些东西。 现在我需要以快速简单的方式对这些项目进行排序。 下拉选择的值为数字。
对象链接对我的问题有用吗? 如果您的回答是肯定的,请说明。
您可以创建一个这样的小实用程序方法来对DropDownList的项进行排序。
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);
}
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's Items by descending
SortListControl(MyDropDownList, false);
}
没有代码就很难回答你的问题。 但这很可能是你在寻找的东西。 IEnumerable.OrderBy()
根据键按升序对序列的元素进行排序。
用这个 :
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();
以简单的方式对下拉列表项进行排序。 首先通过适配器填充数据集,然后从数据集填充数据视图,并使用所需的列对数据视图进行排序。最后将下拉列表与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
第3步:检查数据集是否为空。 如果非空,则创建DataView对象并使用sorted选项填充它并绑定下拉列表,如下所示:
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");
}
您可以将其设置为SortedList,然后只调用list.Sort()方法。
您可以将列表设置为数据源,并使用键/值字段作为DataTextField和DataValueField。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.