0

I have a drop down list that comes from a sqldatasource that is presented in alphabetical order. Because of this, the lists index numbers do not line up at all with the primary keys within the SQL table. 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?

4

4 回答 4

1

Garrison Neely 的回答不太奏效,但它让我走上了正轨。这最终奏效了:

            int i = 0;
            foreach (var item in catagoryDropDown.Items)
            {
                if (item.ToString().Equals("Sick Leave"))
                {
                    catagoryDropDown.SelectedIndex = i;
                    break;
                }
                i++;
            }
于 2013-07-16T12:49:49.070 回答
1
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;
}

添加了 .ToLower() ,因为当字符串不担心大小写时,它会使事情变得更容易。

于 2013-07-15T21:11:28.820 回答
0

尝试这个:

catagoryDropDown.SelectedValue = catagoryDropDown.Items.FindByText("Sick Leave").Value;
于 2013-07-15T21:09:55.460 回答
0

试试这个,我很确定它会起作用:

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

确保该值之前存在于数据源(ddl 绑定的)中。

于 2013-10-01T23:05:49.367 回答