Using the ListBox to select list items.
<%@ Page Language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<script runat="server">
protected void btnAdd_Click(object sender, EventArgs e)
{
ListItem item = lstAllProducts.SelectedItem;
if (item != null)
{
lstAllProducts.Items.Remove(item);
lstFavoriteProducts.ClearSelection();
lstFavoriteProducts.Items.Add(item);
}
}
protected void btnRemove_Click(object sender, EventArgs e)
{
ListItem item = lstFavoriteProducts.SelectedItem;
if (item != null)
{
lstFavoriteProducts.Items.Remove(item);
lstAllProducts.ClearSelection();
lstAllProducts.Items.Add(item);
}
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
foreach (ListItem item in lstFavoriteProducts.Items)
lblResults.Text += "<li>" + item.Text;
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<body>
<form id="form1" runat="server">
<asp:ListBox
id="lstAllProducts"
DataSourceID="srcProducts"
DataTextField="Title"
DataValueField="Id"
Runat="server" />
<asp:Button
id="btnAdd"
Text=">"
ToolTip="Add List Item"
Runat="server"
OnClick="btnAdd_Click" />
<br />
<asp:Button
id="btnRemove"
Text="<"
ToolTip="Remove List Item"
Runat="server"
OnClick="btnRemove_Click" />
</div>
<asp:ListBox
id="lstFavoriteProducts"
Runat="server" />
</div>
<asp:Button
id="btnSubmit"
Text="Submit Form"
Runat="server" OnClick="btnSubmit_Click" />
</p>
<asp:Label
id="lblResults"
EnableViewState="false"
Runat="server" />
<asp:SqlDataSource
id="srcProducts"
SelectCommand="SELECT Id, Title FROM Products"
ConnectionString="<%$ ConnectionStrings:Products %>"
Runat="server" />
</form>
</body>
</html>
File: Web.config
<configuration>
<connectionStrings>
<add name="Products"
connectionString="Data Source=.\SQLEXPRESS;
AttachDbFilename=|DataDirectory|MyDatabase.mdf;Integrated Security=True;User Instance=True" />
</connectionStrings>
</configuration>
Related examples in the same category