blogspot visit counter

Wednesday, 15 May 2013

listbox multiple selection asp.net

listbox multiple selection asp.net
Introduction : -

A ListBox control provides an interface to display a list of items. Users can select one or more items from the list. A ListBox may be used to display multiple columns and these columns may have images and other controls.
In this tutorial, we will learn how to create a ListBox control at design-time as well as at run-time. We will also see how to create a multiple-column ListBox control with single and multiple selections. This article also covers most of the properties and methods of the ListBox control.

Description :-
 
This example shows the basics on how to save multiple selected items from the ASP.Net ListBox control to the database in ASP.Net. Please note that this example requires a basic knowledge of ADO.NET.

STEP1: Setting up the User Interface (GUI)

For the simplicity of this demo, I just set up the web form like below:



<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <style type="text/css">
        #form1
        {
            text-align: center;
        }
    </style>
</head>
<body>
    <form id="form1" runat="server">
    <div>

        Employee names: <br />

        <asp:ListBox ID="ListBox1" runat="server" Height="149px" SelectionMode="Multiple" Width="113px">

        <asp:ListItem>chitranjan</asp:ListItem>

        <asp:ListItem>ranjan</asp:ListItem>

        <asp:ListItem>Rohan</asp:ListItem>

        <asp:ListItem>Shohan</asp:ListItem>

        <asp:ListItem>Ronak</asp:ListItem>

        <asp:ListItem>Ranu</asp:ListItem>

        <asp:ListItem>Raja</asp:ListItem>

        <asp:ListItem>Papu</asp:ListItem>

        </asp:ListBox>  

    </div>

    <br />

    <asp:Button ID="Button1" runat="server" Text="Save" onclick="Button1_Click" />
    </form>
</body>
</html>

Notes: 

* Since the ListBox is intended for multiple item selections then we need to set the SelectionMode attribute of the ListBox to Multiple

* To do multiple Selections in the ListBox then just hold Ctrl key and select the items you want.
STEP 2: Creating a Simple Database Table

In this demo, we are going to store the selected employee names that is selected from the ListBox to the database. So let's now create a simple table that contains the following Column Names:
Note [-id  is auto increment]





Note: I set the Id to auto increment so that the id will be automatically generated for every new added row. To do this select the Column name “Id” and in the column properties set the “Identity Specification” to yes.

STEP 3: Declaring the necessary name spaces:

Be sure to add the following namespaces below:



using System.Data.SqlClient;
using System.Collections.Specialized;
using System.Text;



We need to declare the namespaces above so that we can use the SqlClient, StrngCollections and StringBuilder built-in methods in our codes later.

STEP4: Creating the Method for Multiple Inserts.

Here are the code blocks below:



protected void Button1_Click(object sender, EventArgs e)
    {
        StringCollection sc = new StringCollection();
        foreach (ListItem item in ListBox1.Items)
        {

            if (item.Selected)
            {

                sc.Add(item.Text);

            }

        }

        InsertRecords(sc);
    }


    private void InsertRecords(StringCollection sc)
    {
        SqlConnection conn = VoterConnectionDB.GetConnection();
        StringBuilder sb = new StringBuilder(string.Empty);
        foreach (string item in sc)
        {

            //For pass the more than one column then use this format
            const string sqlStatement = "INSERT INTO Table1 (city,contactno,Employees) VALUES";
            sb.AppendFormat("{0}('{1}','{2}','{3}');",sqlStatement,"indore","0000000000", item);
           // sb.AppendFormat("{0}('{1}','{2}','{3}');", sqlStatement, sqlStatement[0], sqlStatement[1], item);
           // sb.AppendFormat("{0}('{1}','{2}','{3}');", sqlStatement, txtcity_txt, txt_contact.Text, item);
        }

        try
        {
         SqlCommand cmd = new SqlCommand(sb.ToString(), conn);
            cmd.CommandType = CommandType.Text;
            cmd.ExecuteNonQuery();
            Page.ClientScript.RegisterClientScriptBlock(typeof(Page), "Script", "alert('Records Successfuly Saved!');", true);
        }

        catch (System.Data.SqlClient.SqlException ex)
        {
            string msg = "Insert Error:";
            msg += ex.Message;
            throw new Exception(msg);
        }
        finally
        {
            conn.Close();
        }

    }

STEP5: Compile and Run the Application.

The page output would look something like below:

On Run Time


 On Selection The Name From the ListBox And Press Save Button

Genrate the Pupop After Insert The Record In the database image as shown below




Download sample code attached






WCF Service Example Step By Step For Beginners

8 comments:

  1. very usefull notes and we need more information on this topic please post updated data . thanks for your post.
    Dot net online tutorials


    ReplyDelete
    Replies
    1. Thank ' s for your comment.New information on this topic is coming soon..

      Delete
  2. This post is very Nice and Clear for use multiple selection of list box .i am very happy for your post. please provide more example related to this post

    ReplyDelete
  3. Besant Tech Reviews,

    This page is dedicated for our Besant Technologies Reviews by our students. Please give your reviews here,

    Besant Technologies Reviews

    ReplyDelete

  4. This page is dedicated for our Besant Technologies Reviews by our students. Please give your
    reviews here,

    Besant Technologies Reviews

    ReplyDelete
  5. This page is dedicated for our Besant Technologies Reviews by our students. Please give your reviews here,

    Besant Technologies Reviews

    ReplyDelete

Related Posts Plugin for WordPress, Blogger...