如何在dropdownlist.databind()之前对数据进行排序 [英] how to sort data before dropdownlist.databind()

查看:80
本文介绍了如何在dropdownlist.databind()之前对数据进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在绑定下拉列表之前,我使用以下代码对数据进行排序。会发生什么''SELECT''也正在排序。如何避免这种情况并保留首选位置。

I use the following code to sort data before binding a dropdownlist. What happens is that ''SELECT'' is also getting sorted. How to avoid this and retain the position of select in the first place.

adds1.Add("SELECT");
        for (int i = 0; i < ds1.Tables[0].Rows.Count; i++)
        {
            adds1.Add(ds1.Tables[0].Rows[i].ItemArray[0].ToString().ToLower());
            name1 = ds1.Tables[0].Rows[i]["block_name"].ToString().ToLower();
        }
        adds1.Sort((x, y) => string.Compare(x, y));
        DropDownList7.DataSource = adds1;
        DropDownList7.DataBind();

推荐答案

我假设adds1是List< t>某种,所以你可以在排序后使用adds1.Insert(0,SELECT)。

这将在列表的第0位添加SELECT(列表顶部)
I assume adds1 is a List<t> of some sort, so you can use adds1.Insert(0, "SELECT") after you sort.
This will add the "SELECT" at location 0 of the list (top of the list)


更改您的代码。写:



Change your code. Write:

for (int i = 0; i < ds1.Tables[0].Rows.Count; i++)
{
adds1.Add(ds1.Tables[0].Rows[i].ItemArray[0].ToString().ToLower());
name1 = ds1.Tables[0].Rows[i]["block_name"].ToString().ToLower();
}
adds1.Sort((x, y) => string.Compare(x, y));
DropDownList7.DataSource = adds1;
DropDownList7.DataBind();

ListItem li = new ListItem();
li.Text = "Select";
li.Value = "0";
DropDownList7.Items.Insert(0,li);
DropDownList7.SelectedIndex = 0;





这样你将所有已排序的项目添加到您的下拉列表中,然后在第一个位置插入新项目选择。



This way you are adding all the sorted items to your dropdownlist and then inserting a new item "Select" at first position.


尝试:

Try:
for (int i = 0; i < ds1.Tables[0].Rows.Count; i++)
{
    adds1.Add(ds1.Tables[0].Rows[i].ItemArray[0].ToString().ToLower());
    name1 = ds1.Tables[0].Rows[i]["block_name"].ToString().ToLower();
}
adds1.Sort((x, y) => string.Compare(x, y));
adds1.Insert(0, "SELECT");
DropDownList7.DataSource = adds1;
DropDownList7.DataBind();





参考: MSDN:List< t> .Insert方法 [ ^ ]


这篇关于如何在dropdownlist.databind()之前对数据进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆