0

此问题已解决,请参阅帖子下方的评论

我的代码有一个问题让我感到困惑:我有一个 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 查询参数“?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;
            }
        }

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

错误 CS0103:当前上下文中不存在名称“SelectedValue”

(此消息是从德语翻译而来,可能与英语略有不同)

任何帮助表示赞赏。

4

1 回答 1

0

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

//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;
    }
}
于 2016-03-30T09:12:44.137 回答