문제

I'm trying to do a logic here where by if an item from db exists in part of the dropdownlist ListItem it will have that item selected, else it will display the new item in a textbox and have the "Others" selected in the dropdownlist.

This is what I have so far

string gameData = readGame["gTitle"].ToString();
string gameTitle = ddlgameTile.Items.ToString();

if (printHouseData == gameTitle)
{
   ddlgameTile.SelectedIndex = ddlgameTile.Items.IndexOf(ddlgameTile.Items.FindByValue(gameData));
}
else
{
   txtNewGame.Text = readGame["gTitle"].ToString();
   ddlgameTile.SelectedIndex = ddlgameTile.Items.IndexOf(ddlgameTile.Items.FindByValue("Others"));
}

I tried using Foreach loop and for loop, it still would not work (properly). It only gets the if-else logic by the last ListItem which is the "Others".

도움이 되었습니까?

해결책

Assuming that gameData is the db item you want to select if it does exist, you can use ListItemCollection.FindByValue to get the item or null if it does not exist. Then you can set DropDownList.SelectedValue to select it:

string selectedValue = "Others";
if(ddlgameTile.Items.FindByValue(gameData) != null)
    selectedValue = gameData;
ddlgameTile.SelectedValue = selectedValue;

However, if you have set the DataValueField and DataTextField you have to use FindByText.

다른 팁

How about something like this?

        var compareTo = new ListItem("Title","Value");
        if (ddl.Items.Contains(compareTo))
        {
            var selectedIndex = ddl.Items.IndexOf(compareTo);
        }
        else
        {
            var selectedIndex = 
                 ddl.Items.IndexOf(new ListItem { Value = "Others", Text = "Others" });
        }

Assuming I have the context of what you're trying to achieve right, try this:

foreach (string gameTitle in ddlgameTile.Items)
{
    if (printHouseData == gameTitle)
    {
        ddlgameTile.SelectedIndex = ddlgameTile.Items.IndexOf(ddlgameTile.Items.FindByValue(gameData));
    }
    else
    {
        txtNewGame.Text = readGame["gTitle"].ToString();
        ddlgameTile.SelectedIndex = ddlgameTile.Items.IndexOf(ddlgameTile.Items.FindByValue("Others"));
    }
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top