如何将DropDownList选择的值分配给SqlDataSource? [英] How to assign DropDownList selected value to SqlDataSource?
问题描述
我有一个从本地db获取数据的列表视图,并且有一个DropDownList可以按类型过滤asp:list视图中的项目.我是用向导完成的.
I have this list view that fetches data from local db, and there is a DropDownList to filter the items in asp:list view by their type. I did it with wizard.
将它们绑定后.它只能按过滤器显示项目.但是,当我同时需要两个选项时,我无法显示所有项目.
After I bind them. it could only show items by filter. However, I could't show all items while I want both options.
所以我决定将它们自己绑定在后面的代码中,但无法得到任何结果,这是我的下拉列表索引更改事件中的代码:
So I decided to bind them myself in code behind, and I couldn't get any result here's my code in drop down list index changed event:
protected void BookListddl_SelectedIndexChanged(object sender, EventArgs e)
{
if (BookListddl.SelectedIndex == 0)
{
SqlDataSource dataSource = new SqlDataSource(ConfigurationManager.ConnectionStrings[0].ConnectionString
, "SELECT * FROM BookTbl");
dataSource.SelectCommandType = SqlDataSourceCommandType.Text;
dataSource.SelectCommand = "SELECT * FROM BookTbl";
dataSource.DataBind();
ListView1.DataSourceID = dataSource.ID;
ListView1.DataBind();
}
else
{
SqlDataSource dataSource = new SqlDataSource(ConfigurationManager.ConnectionStrings[0].ConnectionString
, "SELECT * FROM [BookTbl] WHERE [TypeId] = '" + BookListddl.SelectedValue + "'");
dataSource.SelectCommandType = SqlDataSourceCommandType.Text;
dataSource.SelectCommand = "SELECT * FROM [BookTbl] WHERE [TypeId] = '" + BookListddl.SelectedValue + "'";
dataSource.DataBind();
ListView1.DataSourceID = dataSource.ID;
ListView1.DataBind();
}
推荐答案
如果使用 SqlDataSource ,最简单的方法是将数据绑定在最前面.
If you use SqlDataSource, the easiest way will be to bind data at front.
注意:我创建了 TypeId 作为整数.
Note: I created TypeId as integer.
如果DropDownList的选定值为-1 ,则 SqlDataSource 将返回所有项目.
If DropDownList's selected value is -1, SqlDataSource will return all items.
<asp:DropDownList ID="BookListddl" runat="server" AutoPostBack="True">
<asp:ListItem Text="All" Value="-1" />
<asp:ListItem Text="Fiction" Value="1" />
<asp:ListItem Text="None Fiction" Value="2" />
</asp:DropDownList>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
SelectCommand="SELECT * FROM [BookTbl] WHERE [TypeId] = @TypeId OR @TypeId = -1">
<SelectParameters>
<asp:ControlParameter ControlID="BookListddl"
PropertyName="SelectedValue"
Name="TypeId"
Type="Int32" />
</SelectParameters>
</asp:SqlDataSource>
这篇关于如何将DropDownList选择的值分配给SqlDataSource?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!