C# 如何在asp.net中将数据绑定到dropdownlist后查找值?

C# 如何在asp.net中将数据绑定到dropdownlist后查找值?,c#,asp.net,data-binding,C#,Asp.net,Data Binding,这让我快发疯了。我有一个dropdownlist,并且绑定到一个sql表 ddlTypeOntslag.DataTextField = "CodeDesc"; ddlTypeOntslag.DataValueField = "DTCODE"; ddlTypeOntslag.DataSource = dal.ListTypeOntslag(); ddlTypeOntslag.AppendDataBoundItems = true;

这让我快发疯了。我有一个dropdownlist,并且绑定到一个sql表

        ddlTypeOntslag.DataTextField = "CodeDesc";
        ddlTypeOntslag.DataValueField = "DTCODE";
        ddlTypeOntslag.DataSource = dal.ListTypeOntslag();
        ddlTypeOntslag.AppendDataBoundItems = true;
        ddlTypeOntslag.DataBind();
我可以在dropdownlist中看到值,但每当我尝试以编程方式选择一个值时,要么出现错误,要么什么都没有发生。 我尝试了以下方法:

ddlTypeOntslag.Items.FindByValue("2").Selected = true;
-----------
ListItem selectedListItem = ddlTypeOntslag.Items.FindByValue("2");

                if (selectedListItem != null)
                {
                    selectedListItem.Selected = true;
                    Response.Write("found it");
                }
-----------
ddlTypeOntslag.SelectedIndex = ddlTypeOntslag.Items.IndexOf(ddlTypeOntslag.Items.FindByValue("2"));
似乎什么都不管用。我尝试过使用其他值,或者FindByText,什么都没有。 你知道会出什么问题吗? PS:我已经在数据绑定后设置了选择代码。
PS2:我也在databound事件中设置了,但它不起作用。

您到底想做什么?您选择了3次下拉列表,其值为2。是否很难理解它?你为什么不仔细阅读我说的内容:我已经尝试了以下内容。是的,经过你的编辑,现在清楚了:你能告诉我你面临的错误是什么吗?所有这3种方法都应该有效,如果值中有空格,请在下拉列表中进行检查。@IForti:在执行此操作之前,ddlTypeOntslag.Items.FindByValue2.Selected=true;添加ddltypeontslavk.ClearSelection;不这样做显然会导致错误,因为不能一次选择两个值。看看这是否行得通。