我將數據綁定複選框列表添加到SQL Server中,該數據庫顯示我的數據庫的「名稱」(使用電影作爲示例:喜劇,動作,恐怖)列中的項目。該複選框列表充當過濾器,因此當用戶選中複選框時,相關電影將出現。查看複選框列表後,在datalist中顯示項目
我已經設法數據綁定了checkboxlist。複選框的值具有綁定到數據庫的「CategoryId」的值。但是我不知道如何進一步進行,即在複選框被選中時顯示電影海報(圖片)的數據列表。
例如,當我選中「喜劇」複選框時,將出現屬於該類型的電影海報(datalist)。
這裏是我迄今所做的,Default.aspx的代碼:
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:DVDShopConnectionString %>"
SelectCommand="SELECT [ProductID], [Title], [Image1FileName] FROM [Product]"></asp:SqlDataSource>
<asp:SqlDataSource ID="SqlDataSource2" runat="server"
ConnectionString="<%$ ConnectionStrings:DVDShopConnectionString %>"
SelectCommand="SELECT * FROM [Category]"></asp:SqlDataSource>
<br />
<asp:CheckBoxList ID="CheckBoxList1" runat="server" AutoPostBack="True"
DataSourceID="SqlDataSource2" DataTextField="Name" DataValueField="CategoryID"
onselectedindexchanged="CheckBoxList1_SelectedIndexChanged">
</asp:CheckBoxList>
<asp:datalist runat="server" DataKeyField="ProductID" DataSourceID="SqlDataSource1"
RepeatColumns="4" ID="DataList1" >
<ItemTemplate>
<asp:Image ID="Image1" runat="server"
ImageUrl='<%# Eval("Image1FileName", "~/ProductImages/{0}") %>' />
<br />
<asp:Label ID="TitleLabel" runat="server" Text='<%# Eval("Title") %>' />
<br />
<br />
<br />
</ItemTemplate>
</asp:datalist>
背後代碼:
private SqlDataReader getReader()
{
//get connection string from web.config
string strConnectionString = ConfigurationManager.ConnectionStrings["DVDShopConnectionString"].ConnectionString;
SqlConnection myConnect = new SqlConnection(strConnectionString);
string strCommandText = "SELECT CategoryID, Name from Category";
SqlCommand cmd = new SqlCommand(strCommandText, myConnect);
myConnect.Open();
//DataList1.DataSource = reader;
DataList1.DataBind();
// CommandBehavior.CloseConnection will automatically close connection
SqlDataReader reader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
return reader;
}
protected void CheckBoxList1_SelectedIndexChanged(object sender, EventArgs e)
{
for (int i = 0; i < CheckBoxList1.Items.Count; i++)
{
if (CheckBoxList1.Items[i].Selected == true)
{
//items should be filter here..
}
}
}
任何建議或想法是極大的讚賞。