Tuesday, September 8, 2015

Multiple select Listbox, C# asp.net

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default17.aspx.cs" Inherits="Default17" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <asp:ListBox ID="lstFruits" runat="server" SelectionMode="Multiple">
    <asp:ListItem Text="Mango" Value="01" />
    <asp:ListItem Text="Apple" Value="02" />
    <asp:ListItem Text="Banana" Value="03" />
    <asp:ListItem Text="Guava" Value="04" />
    <asp:ListItem Text="Orange" Value="05" />
</asp:ListBox>
<asp:Button ID="Button1" Text="Submit" runat="server" OnClick="Submit" />
    </div>
    <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
        DataKeyNames="LT,FY,BU,MedCostID" DataSourceID="SqlDataSource1">
        <Columns>
            <asp:BoundField DataField="LT" HeaderText="LT" ReadOnly="True"
                SortExpression="LT" />
            <asp:BoundField DataField="FY" HeaderText="FY" ReadOnly="True"
                SortExpression="FY" />
            <asp:BoundField DataField="BU" HeaderText="BU" ReadOnly="True"
                SortExpression="BU" />
            <asp:BoundField DataField="MedCostID" HeaderText="MedCostID" ReadOnly="True"
                SortExpression="MedCostID" />
            <asp:BoundField DataField="MCE_FSC1_Change" HeaderText="MCE_FSC1_Change"
                SortExpression="MCE_FSC1_Change" />
            <asp:BoundField DataField="MCE_FSC1_Date" HeaderText="MCE_FSC1_Date"
                SortExpression="MCE_FSC1_Date" />
         
        </Columns>
    </asp:GridView>
    <asp:SqlDataSource ID="SqlDataSource1" runat="server"
        ConnectionString="<%$ ConnectionStrings:ConnectionString1 %>"
        ></asp:SqlDataSource>
    </form>
</body>
</html>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class Default17 : System.Web.UI.Page
{
    string allItems = "";
    string allItemsql = "";
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void Submit(object sender, EventArgs e)
    {
        string message = "";
        foreach (ListItem item in lstFruits.Items)
        {
            if (item.Selected)
            {
                message += item.Text + " " + item.Value + "\\n";

                allItems += "'"+item.Value+"'," ;

            }
        }
        allItemsql = allItems.Substring(0, allItems.Length - 1);

        SqlDataSource1.SelectCommand = "SELECT * FROM [UserData] where MedCostID in (" + allItemsql + ")";

    }
}