Using the ListBox to select list items. : ListBox « Asp Control « ASP.Net






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="&gt;"
        ToolTip="Add List Item"
        Runat="server" 
        OnClick="btnAdd_Click" />
    <br />
    <asp:Button
        id="btnRemove"
        Text="&lt;"
        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

1.Set static value for asp:listbox (VB.net)
2.asp:listbox: On selected index changed
3.Get selected index, text and value from asp:listbox (VB.net)
4.Change background color for asp:listbox (VB.net)
5.Allowing Multiple Selections in a ListBox Control (VB.net)
6.Get selected index from asp:listbox (VB.net)
7.Get selected item from ListBox (C#)
8.Add ListItem to ListBox