ASP.Net Code

ASP.Net – Get All Selected Items in a List (ListBox) Control

With ASP, you could retrieve all selected values of a select list by parsing the QueryString. Now that ASP.Net is object-oriented and all controls are stateful however, there is a much more reliable method to retrieve the value (or text!) of each selected item in any list control (ListBox, CheckBoxist, RadioButtonList). This code snippet will also illustrate how to insert each item as a unique row in a database table; or in other words performing multiple INSERTS at once, with one SqlCommand.

The example is of adding a user to a database, and selecting the languages that the user speaks. The languages ListBox is DataBound to a languages data table. There is a RequiredFieldValidator to ensure that at least one language is selected.


First Name<span class="required">*</span><br />
<asp:TextBox runat="server" ID="NewUserName" CssClass="text" />

<asp:RequiredFieldValidator runat="server" ID="ValNewUserName" ControlToValidate="NewUserName" Display="Dynamic" ErrorMessage="User name is required" />    
<br />
Language(s)<span class="required">*</span><br />
<asp:ListBox ID="ListNewUserLanguages" DataSourceID="DSLanguages" DataValueField="id" DataTextField="language" runat="server" Rows="10" SelectionMode="Multiple" /> 

<asp:SqlDataSource ID="DSLanguages" runat="server" SelectCommand="SELECT id, language from languages ORDER BY language" ConnectionString="<%$ ConnectionStrings:ConnDB %>" />                

<asp:RequiredFieldValidator runat="server" ID="ValLanguages" ControlToValidate="ListNewUserLanguages" Display="Dynamic" ErrorMessage="Please choose at least one language" />               

And here's the code to get each select language. I assume that already know how to INSERT the new user, and retrieve the new user ID created. The data structure is relational, so the languages will be inserted into a table called 'user_languages'.

// start with a blank SQL statement
string sql = "";
for (int i = 0; i < ListNewUserLanguages.Items.Count; i++) { if(ListNewUserLanguages.Items[i].Selected) // append each language as another INSERT statement sql += string.Format("INSERT INTO user_languages (user_id, language_id) VALUES ('{0}','{1}');", UserID, ListNewUserLanguages.Items[i].Value); } string conn = ConfigurationManager.ConnectionStrings["ConnDB"].ConnectionString; SqlConnection ConnSQL = new SqlConnection(conn); ConnSQL.Open(); myCommand = new SqlCommand(sql, ConnSQL); // perform all the inserts at once myCommand.ExecuteNonQuery(); myCommand = null; ConnSQL.Close(); [/code]

Share

1 Comments

  1. Thanks ,thanks, thanks for idea!!

Leave a Reply

Your email address will not be published. Required fields are marked *

*
To prove you're a person (not a spam script), type the security word shown in the picture. Click on the picture to hear an audio file of the word.
Anti-spam image