如何在选择项值之前加载sql数据源
本文关键字:加载 sql 数据源 选择 | 更新日期: 2023-09-27 18:29:25
我的asp.net页面上有SQL数据源,当页面加载时出现此错误
"ddlTypes"的SelectedValue无效,因为它不在项列表中。参数名称:值
private void GetQueryString(Uri tempUri)
{
if (HttpUtility.ParseQueryString(tempUri.Query).Get("IntrestFocus") != null)
{
ddlTopics.SelectedValue = HttpUtility.ParseQueryString(tempUri.Query).Get("IntrestFocus");
}
else
if (HttpUtility.ParseQueryString(tempUri.Query).Get("Skills") != null)
{
ddlSkills.SelectedValue = HttpUtility.ParseQueryString(tempUri.Query).Get("Skills");
}
else
if(HttpUtility.ParseQueryString(tempUri.Query).Get("Type") != null)
{
ddlTypes.SelectedValue = HttpUtility.ParseQueryString(tempUri.Query).Get("Type");
}
}
<asp:SqlDataSource ID="SqlDSTypes" runat="server" ConnectionString="<%$ ConnectionStrings:SiteSqlServer %>" SelectCommand="SELECT * FROM [Types]"></asp:SqlDataSource>
<asp:DropDownList CssClass="selectpicker mobile-stack select-type" data-style="lts-white font-black drop-shadow select-height" ID="ddlTypes" runat="server" DataSourceID="SqlDSTypes" DataTextField="Description" DataValueField="Id" AppendDataBoundItems="True" ClientIDMode="Static">
<asp:ListItem Value="0">Select a Type</asp:ListItem>
</asp:DropDownList>
这是您的主要选项:
private void GetQueryString(Uri tempUri)
{
ddlTopics.DataSource = SqlDSTypes.Select(DataSourceSelectArguments.Empty);
ddlTopics.DataBind();
//Put your logic here, behind databind ...
if (HttpUtility.ParseQueryString(tempUri.Query).Get("IntrestFocus") != null)
{
ddlTopics.SelectedValue = HttpUtility.ParseQueryString(tempUri.Query).Get("IntrestFocus");
}
else
if (HttpUtility.ParseQueryString(tempUri.Query).Get("Skills") != null)
{
ddlSkills.SelectedValue = HttpUtility.ParseQueryString(tempUri.Query).Get("Skills");
}
else
if(HttpUtility.ParseQueryString(tempUri.Query).Get("Type") != null)
{
ddlTypes.SelectedValue = HttpUtility.ParseQueryString(tempUri.Query).Get("Type");
}
}
当您选择上面的答案时,还要确保没有设置DataSourceID。
然而,还有另一种可能性,那就是使用OnDataBound
事件并将DropDownList
逻辑放入其中。它将在DropDownList
数据绑定后被激发,然后:
你的代码背后:
protected function ddlTopics_DataBound(Object sender, EventArgs e)
{
//Put your logic here, behind databind ...
if (HttpUtility.ParseQueryString(tempUri.Query).Get("IntrestFocus") != null)
{
ddlTopics.SelectedValue = HttpUtility.ParseQueryString(tempUri.Query).Get("IntrestFocus");
}
else
if (HttpUtility.ParseQueryString(tempUri.Query).Get("Skills") != null)
{
ddlSkills.SelectedValue = HttpUtility.ParseQueryString(tempUri.Query).Get("Skills");
}
else
if(HttpUtility.ParseQueryString(tempUri.Query).Get("Type") != null)
{
ddlTypes.SelectedValue = HttpUtility.ParseQueryString(tempUri.Query).Get("Type");
}
}
您的aspx:
<asp:DropDownList ID="ddlTopics" OnDataBound="ddlTopics_DataBound" runat="server" ...
后者可能是最简洁的选择。