简体   繁体   English

使用字符串设置下拉列表的默认选择

[英]using string to set default selection of drop down list

I have a drop down list that comes from a sqldatasource that is presented in alphabetical order. 我有一个下拉列表,该列表来自以字母顺序显示的sqldatasource。 Because of this, the lists index numbers do not line up at all with the primary keys within the SQL table. 因此,列表索引号根本不与SQL表中的主键对齐。 I need to be able to set the drop down list's selection on page load based on primary key information I have. 我需要能够基于我拥有的主键信息在页面加载时设置下拉列表的选择。

<asp:DropDownList ID="catagoryDropDown" runat="server" DataSourceID="SqlDataSource3"
     DataTextField="Catagory" DataValueField="PK_SupportCatagory" CssClass="dropDownList">
</asp:DropDownList>
<asp:SqlDataSource ID="SqlDataSource3" runat="server" ConnectionString="<%$     
     ConnectionStrings:ApplicationServices %>"
     SelectCommand="SELECT [PK_SupportCatagory], [Catagory] FROM [SupportCatagory] ORDER BY CASE  
     WHEN [PK_SupportCatagory] = 1 THEN 1 ELSE 2 END, [Catagory]">
</asp:SqlDataSource>

My thought is to get the string by querying the database using that to set the drop down list appropriately. 我的想法是通过查询数据库来获取字符串,并使用它来适当设置下拉列表。

catagoryDropDown.SelectedValue = "Sick Leave";

The above does not work. 上面的方法不起作用。 How would I accomplish this? 我将如何完成? Is there a better way to do this? 有一个更好的方法吗?

var selectedIndex = -1;

for(int i = 0; i < catagoryDropDown.Items.Count; i++)
{
    if(catagoryDropDown.Items[i].Text.ToLower() == "sick leave")
    {
        selectedIndex = i;
        break;
    }
}

if(selectedIndex > -1)
{
    catagoryDropDown.SelectedIndex = selectedIndex;
}

Added the .ToLower() because it makes things easier when strings don't have case worries. 添加了.ToLower(),因为它在字符串不区分大小写的情况下使事情变得更容易。

Garrison Neely's answer did not quite work but it got me on the right track. Garrison Neely的回答虽然没有奏效,但它使我步入正轨。 This ultimatly worked: 这最终奏效了:

            int i = 0;
            foreach (var item in catagoryDropDown.Items)
            {
                if (item.ToString().Equals("Sick Leave"))
                {
                    catagoryDropDown.SelectedIndex = i;
                    break;
                }
                i++;
            }

尝试这个:

catagoryDropDown.SelectedValue = catagoryDropDown.Items.FindByText("Sick Leave").Value;

Try this One, I am pretty sure it will work: 试试这个,我很确定它会起作用:

ddl.SelectedIndex = ddl.Items.IndexOf(ddl.Items.FindByText(Convert.ToString(Any Value)));

Make sure the value exist in the datasource (to which the ddl is bound) before. 确保该值之前存在于数据源(绑定了ddl的数据源)中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM