ASP.NET DropDownList.SelectedValue丢失了i!nPostBack

时间:2016-03-30 08:27:14

标签: c# asp.net postback dropdown list.selectedvalue

此问题已解决,请参阅帖子

下方的评论

我的代码有问题让我感到困惑: 我有一个ASP.NET DropDownList(简单,不在gridview中等等),它是静态数据绑定到数据库查询。另外,我在标记中添加了一个列表项:

<asp:DropDownList ID="ddDeviceSelector" runat="server" DataSourceID="CryringDB_InventoryAssets" DataTextField="Identifier" DataValueField="RowID" AutoPostBack="True" OnTextChanged="ddDeviceSelector_IndexChanged" ToolTip="Select a device by name" AppendDataBoundItems="True" Width="300px">
    <asp:ListItem>-- Select Device OR Enter Data of New Device --</asp:ListItem>
</asp:DropDownList>
<asp:SqlDataSource ID="CryringDB_InventoryAssets" runat="server" connectionString="<%$ ConnectionStrings:CMSValuesExplicitUser %>" SelectCommand="SELECT valueColumn, textColumns FROM myTable"></asp:SqlDataSource>

我可以使用URL查询参数调用该页面&#34;?rid = ...&#34;其中rid包含列表中某个特定项的值。当我尝试解析rid并按值选择列表中的项时,DropDownList.SelectedValue不会被设置。 Page_Load代码:

    protected void Page_Load(object sender, EventArgs e)
    {
        // Code to interpret the parameter rid (RowID) in the URL
        // provides functionality to open formAssetDetails of an individual object.
        if (!IsPostBack)
        {
            ddDeviceSelector.DataBind();
            setUiPropertiesByMode(classConstants.displayMode);

            String rowID = null;
            rowID = Request.QueryString["rid"];

            if (rowID != null)
            {
                setUiPropertiesByMode(classConstants.editMode);
                ddDeviceSelector.Enabled = true;
                ddDeviceSelector.Enabled = true;
                ddDeviceSelector.SelectedValue = rowID;
            }
        }

代码执行没有问题,但我在调试器中看到一条错误消息(第34行后的断点; ddDeviceSelector.SelectedValue = rowID;&#34;)

  

错误CS0103:名称&#39; SelectedValue&#39;在当前上下文中不存在

(此信息由德语翻译,英语可能略有不同)

任何帮助表示感谢。

1 个答案:

答案 0 :(得分:0)

尝试在下拉列表的DataBound事件中设置所选值,这将确保您的下拉列表在尝试设置selectedvalue之前完全数据绑定数据,请记住委派此方法:

//In your designer file
ddDeviceSelector.DataBound += new System.EventHandler(ddDeviceSelector_DataBound);

protected void ddDeviceSelector_DataBound(object sender, EventArgs e)
{
    String rowID = null;
    rowID = Request.QueryString["rid"];

    if (rowID != null)
    {
        setUiPropertiesByMode(classConstants.editMode);
        ddDeviceSelector.Enabled = true;
        ddDeviceSelector.Enabled = true;
        ddDeviceSelector.SelectedValue = rowID;
    }
}