Geeks With Blogs

News

Microsoft MVP


DZone MVB


Moderator at CodeASP.NET


Quiz Master







free counters
Free counters
Added on January 19,2012


Follow Me @vmsdurano

A bit About Me



Disclaimer
The opinions expressed herein are my own personal opinions and does not represent the opinions of my employers. Nor does it represent the opinion of my dog, because I don’t have one.


Vinz' Blog (ProudMonkey) "Code, Beer and Music ~ my way of being a programmer"

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

STEP 1: 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>Untitled Page</title>
</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>Vinz</asp:ListItem>
             <asp:ListItem>Jhen</asp:ListItem>
             <asp:ListItem>Chris</asp:ListItem>
             <asp:ListItem>Shynne</asp:ListItem>
             <asp:ListItem>Chu</asp:ListItem>
             <asp:ListItem>Mark</asp:ListItem>
             <asp:ListItem>Lilian</asp:ListItem>
             <asp:ListItem>Rod</asp:ListItem>
             <asp:ListItem>Glendzy</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:

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.

STEP 4: Creating the Method for Multiple Inserts.

Here are the code blocks below:

private string GetConnectionString(){
        //Where MyDBConnectionString is the connetion string that was set up in the web config file
        return System.Configuration.ConfigurationManager.ConnectionStrings["MyDBConnectionString"].ConnectionString;
}

private void InsertRecords(StringCollection sc){

        SqlConnection conn = new SqlConnection(GetConnectionString());
        StringBuilder sb = new StringBuilder(string.Empty);

        foreach (string item in sc)
        {
            const string sqlStatement = "INSERT INTO Table1 (Employees) VALUES";
            sb.AppendFormat("{0}('{1}'); ", sqlStatement, item);
        }
        try
        {
            conn.Open();
            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();
        }
}

protected void Page_Load(object sender, EventArgs e){

}

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);
}



As you can see, the code above is very straight forward and self explanatory.

STEP5: Compile and Run the Application.

The page output would look something like below:


Clicking the Save Button, will execute the method InsertRecords for storing the selected items from the ListBox Control to the database and displays a pop up message informing you that the "Records was successfully Saved"!.


That's it! Hope you will find this example useful!

Technorati Tags: ,,
Posted on Sunday, May 31, 2009 7:11 PM ADO.NET , ASP.NET , C# | Back to top


Comments on this post: ListBox Control: Save Multiple Selected Items in the Database

# re: ListBox Control: Save Multiple Selected Items in the Database
Requesting Gravatar...
Help Please!! i cannot get this to work in ASP.
Left by Artie on Jun 18, 2009 8:32 AM

# re: ListBox Control: Save Multiple Selected Items in the Database
Requesting Gravatar...
This is very nice and helpful codding thanks for your team have a nice day .
Left by Rakesh on Oct 05, 2009 5:12 PM

# re: ListBox Control: Save Multiple Selected Items in the Database
Requesting Gravatar...
HI
its was very helpful to me.thanks very much


Regards
Shareef
Left by Yousuf Shareef on Dec 18, 2009 7:24 PM

# re: ListBox Control: Save Multiple Selected Items in the Database
Requesting Gravatar...
Please can I have the code for WinForms C#
Left by Prince on Mar 17, 2010 5:31 PM

# re: ListBox Control: Save Multiple Selected Items in the Database
Requesting Gravatar...
Works like a dream......I struggled for almost a week and in 5 mins it was done using this code.

Too good.

Thanks a Ton.
Left by aditya on Mar 28, 2011 1:17 AM

# re: ListBox Control: Save Multiple Selected Items in the Database
Requesting Gravatar...
Can u plz provide me code for asp.net mvc3 razor view for same (ListBox Control: Save Multiple Selected Items in the Database)
Left by Saransh on Jul 15, 2011 1:50 AM

# re: ListBox Control: Save Multiple Selected Items in the Database
Requesting Gravatar...
i want to do same in my project.
i have new form with list box and buttons.

i want to save selected items from listbox into database.

pls help me.
Left by sandeep on Sep 22, 2011 9:18 PM

# re: ListBox Control: Save Multiple Selected Items in the Database
Requesting Gravatar...
Hi,
It was very helpfull for me but I want insert textbox value into another extra coulmn so how can I do?
Left by sonali on Dec 02, 2011 6:08 PM

# re: ListBox Control: Save Multiple Selected Items in the Database
Requesting Gravatar...
Thanks. Good Work, i learnt from this post and was helpful!
Left by Vinay B Hiraskar on Feb 08, 2012 1:29 PM

# re: ListBox Control: Save Multiple Selected Items in the Database
Requesting Gravatar...
Thanks. Good Work, i learnt from this post and was helpful
Left by manoj on Sep 07, 2012 1:03 PM

# re: ListBox Control: Save Multiple Selected Items in the Database
Requesting Gravatar...
Thanks. Good Work, i learnt from this post and was helpful and good work
Left by manoj on Sep 07, 2012 1:03 PM

comments powered by Disqus

Copyright © Vincent Maverick Durano | Powered by: GeeksWithBlogs.net