Multiselection Listbox to Populate SQL Db using C#

As a newbie to C# and webforms, I'm creating simple application that stores log files to a SQL database: date/time, action, admin_name, server_id. The problem is with the server name/id field. I have a multiselection listbox that successfully populates my entries (server 1, server 2, server 3, etc.) and I can get it to commit a row to the db if I've selected the topmost value in the server field. I don't know how to create a counter so that I can create a row for each of server that has been selected.

Thanks in advance!



First the page_load stuff....

private void Page_Load(object sender, System.EventArgs e)

{

...

if(!IsPostBack)
   {
  
  
    DAL GetAllServers = new DAL();
    DataSet dsServerNames = GetAllServers.GetAllServers();
    LstBoxServers.DataSource = dsServerNames;
    LstBoxServers.DataTextField = "Server_Name";
    LstBoxServers.DataValueField = "Server_Id";
    LstBoxServers.DataBind();
    Console.WriteLine();
   
   
    DAL GetAdmins = new DAL();
    DataSet dsAdmins = GetAdmins.GetAdmins();
    ddlAdmins.DataSource = dsAdmins;
    ddlAdmins.DataTextField = "Admin_Name";
    ddlAdmins.DataValueField = "Admin_Id";
    ddlAdmins.DataBind();
    ddlAdmins.Items.Insert(0,new ListItem("--Select an Admin--",""));
    Console.WriteLine();
   }
  }


Now the actual ButtonSave action code

private void BtnSave_Click(object sender, System.EventArgs e)


SqlConnection sqlCon6 = null;
   try
   {
    sqlCon6 = new
     SqlConnection("Server=mymachinename;database=myservernamehere;uid=sa;password=xxxxxxxxx;");
    SqlCommand sqlAddLog = new SqlCommand ("sqlAddLog", sqlCon6);
    sqlCon6.Open();
    sqlAddLog.CommandType = CommandType.StoredProcedure;
    sqlAddLog.Parameters.Add
     ("@Assigned_To",System.Data.SqlDbType.VarChar,20, "Assigned_To").Value = ddlAdmins.SelectedItem.Text;
    sqlAddLog.Parameters.Add
     ("@Entry_Date_Time",System.Data.SqlDbType.DateTime, 8, "Entry_Date_Time").Value = Calendar1.SelectedDate;
    sqlAddLog.Parameters.Add("@Comments",System.Data.SqlDbType.VarChar,5000, "Comments").Value = TxtAction.Text;
    sqlAddLog.Parameters.Add
     ("@Server_Id",System.Data.SqlDbType.Int, 0, "Server_Id").Value = LstBoxServers.SelectedValue;

    
    sqlAddLog.ExecuteNonQuery();

   }

   catch ( System.Exception Ex )
   {

    LblError.Text =
     Ex.Message;
   }

   finally
   {
    if (sqlCon6 != null)
     sqlCon6.Close();
    Response.Redirect ("ControlPanel.aspx");
   }
   
  }

0
wannaBee
10/13/2005 8:18:10 PM
asp.net.getting-started 91979 articles. 3 followers. Follow

4 Replies
1229 Views

Similar Articles

[PageSpeed] 57

Just iterate through the ListItems in the ListBox.Items array and use those where selected is true to do what you want with them.

Ie.,

foreach (ListItem li in YourListBox.Items)
    if (li.Selected == true
        Response.Write(li.Text +
"<br>");


Hope this helps


It's all over and I'm standin' pretty
In this dust that was a city
If I could find a souvenier
Just to prove the world was here
0
BobT
10/14/2005 3:17:30 AM
Sorry. I wish I knew what to do with your response but I really don't. Thank you, though!

Where would a I put the foreach statement?

Again, thanks.
0
wannaBee
10/14/2005 2:02:23 PM

I modified your code and added the foreach loop.  This code has not been tested.

   try
   {
    sqlCon6 = new
    SqlConnection("Server=mymachinename;database=myservernamehere;uid=sa;password=xxxxxxxxx;");
    SqlCommand sqlAddLog = new SqlCommand ("sqlAddLog", sqlCon6);
    sqlCon6.Open();
    sqlAddLog.CommandType = CommandType.StoredProcedure;

      foreach (ListItem li in LstBoxServers.Items)
      {
         if (li.selected == true)
         {
            sqlAddLog.Parameters.Clear();
            sqlAddLog.Parameters.Add
             ("@Assigned_To",System.Data.SqlDbType.VarChar,20, "Assigned_To").Value = ddlAdmins.SelectedItem.Text;
            sqlAddLog.Parameters.Add
             ("@Entry_Date_Time",System.Data.SqlDbType.DateTime, 8, "Entry_Date_Time").Value = Calendar1.SelectedDate;
            sqlAddLog.Parameters.Add("@Comments",System.Data.SqlDbType.VarChar,5000, "Comments").Value = TxtAction.Text;
            sqlAddLog.Parameters.Add
             ("@Server_Id",System.Data.SqlDbType.Int, 0, "Server_Id").Value = li.Value;

   
            sqlAddLog.ExecuteNonQuery();
         }  
      }
   }


FYI: The opening brace for the second function in your example is missing.


It's all over and I'm standin' pretty
In this dust that was a city
If I could find a souvenier
Just to prove the world was here
0
BobT
10/14/2005 2:33:27 PM
Thank you SO MUCH! I really worked with your first answer but had the foreach in the wrong spot, and also knew that my value was not referencing the foreach correctly. It worked perfectly with a minor case change to li.Selected

Much obliged!
0
wannaBee
10/14/2005 6:39:41 PM
Reply:

Similar Artilces:

Sending SMS using vb.net or C#.net using vb.net or c#.net
Hi  My requirement is I hav one csv file with these fields id,mobilenum,messgae,status.intiallu staus is 0. once i read the all fileds and take that mobile number.using tat mobile number  i need to send sms .after sending sms i shuld change status as 1 How to send sms thru coding (please dont provide any links.if it is provide also please give working links becox i checked codeproject .i didnt get any nice link. and also provide the how to update the status field im csv file   Thank ssandhya   To send SMS, you need some third party SMS providers. if you consul...

Populating a listBox (i.e. <select><option>) from DB using VB.NET
_/_/_/_/_/_/_/_/_/_/_/ _/_/_/_/_/_/_/_/_/_/ _/_/_______/_/_/_/ Hi every one! I am trying to populate a listbox using VB.NET. I am using SQL Server 2000, and the database looks like this: (sport prefixes) Table name: Prefixes ID Prefix ----- ----------- 1 FTBL 2 SCCR 3 TNNS 4 HCKY .... ... There's a list (i.e. <select><option>) on the web form and its id=Prefixes_list. The list is in a .ascx file, and the code for populating...

use VB.NET and C#.NET code in the same C#.NET project
All-- Here is a sample that is "off the beaten path", (at least for me). Is it possible, in an ASP.NET application, using the code-behind page building technique, to have both pages written in VB.NET and pages written C#.NET?At http://www.WebLogicArts.com/DemoList.aspx there is a sample that shows that, (contrary to popular belief), it IS possible to mix ASP.NET pages built with C#.NET with ASP.NET pages built with VB.NET in the same VS.NET 2003 project. Note that this is just a "fun" sample to see if it can be done and I do not recommend this practice as a "standard" way of develo...

Moving value from one ListBox to another ListBox using C#.NET
Hi all, I have displayed a field in ListbBox1 and another field in ListBox2 control from database. I need to move value from one list box to other list box using C#.NET Please, send me the code in C#.NETThanx in advance,Sreeni Rather than posting back the page every time you shift values from one list to other do this with java script. Here it is - http://forums.asp.net/t/1262273.aspx Make sure before any post back you must save values to some place because after post back values wont persist.Hope it helps.-Manas===============================...

Attach SQL DB to SQL Server 2005 using VB.Net
Is there any way to attach a SQL DB to SQL Server 2005 using VB.Net?  If so can you also set security? Can you rephrase your question? Attach SQL DB from which version of SQL server ? Look up books online for sp_attachdb and sp_detachdb.***********************Dinakar NethiLife is short. Enjoy it.*********************** I have a DB that was created in SQL Server 2005.  I have a website that displays data from systems all over the world.  Each system sends it's data to it's own DB.  The customer can then go to a website and see the data at real time.  What ...

used a c#.net to vb.net converter and am now getting a syntax error.
ok I used a cool utility at http://www.kamalpatel.net/ConvertCSharp2VB.aspx to convert some c#.net to vb.net and it spit out a bunch of code which almost works but I am getting a syntax error on this line Imports (StreamReader sr = Shadows Function)() As StreamReader(objResponse.GetResponseStream()) I tried it that way and also like Imports (StreamReader sr = Shadows Function)() As StreamReader(objResponse.GetResponseStream()) but either way gave the same error Compiler Error Message: BC30035: Syntax error. Source Error: Line 26: Line ...

creating ssis packagte for sql server to sql serer using C#.net
Hi friendsdoes any one has code or urls which can help me to create the ssis pacakage which will transfer data from sql server to sql server databaseswith some manipulationsthanks so much Lad LaxmikantPune You are probably in the wrong forum.  This forum is for questions relating to ASP.NET Dynamic Data. thanks,David...

ListBox would not populate; Populate listbox with paramterised value in C#
 hi thereI'm having a problem in populating the listbox with parameterized value, here is my code for procedure in sqlserver2005:drop procedure ado8gocreate procedure ado8(@DepartmentID int, @LastName varchar (50) out )asSELECT      * FROM         tDepartment INNER JOIN tEmployee ON tDepartment.DepartmentID = tEmployee.DepartmentIdWHERE     (tDepartment.DepartmentID = @DepartmentID)print @LastNamegoexec ado8 100,' 'it works fine in sql server shows me all the coulmns etc,I supposed to show a...

How do I populate a listbox from a SQL DB?
Sorry if this is to basic but I am just starting out. Any help is appreciated. Basically I am attempting to populate a listbox with items from a MSSQL DB so the user can select either one or multiple items in that listbox to search on. This sample is a little more than you asked, but it does what you ask also: http://aspnet101.com/aspnet101/aspnet/codesample.aspx?code=listboxfillDavid WierMCP/ASPInsiderASPNet101.com - where to look first!Control Grouper - easily control properties for multiple controls with one control!Calendar Express - The Best HTML Calendar Generator on the web!(...

Using Gridview to populate Sql DB
I'm just curious, I have a grid view that populates from another apps db. Is it possible to save that data from the gridview into another sql db? I only have read access to the db that populates the data, if I could save it to another db I could allow the user to modify the data. Has anyone done this? Sure you could save the gridview contents but why not just use a SELECT INTO query to make a new copy of the data. More info on SELECT INTO at http://www.w3schools.com/Sql/sql_select_into.asp Hope it helpsRegardsJeremyIf this has helped Please: Don't forget to click "Mark as An...

Using a multiselect listbox to populate a datagrid
 Hi,I'm pretty new to vb.net and am trying to develop a website for a school project. I am using a dataset (xsd file) and have a query that populates a listbox with multiselect enabled.When I click an item, it shows my datagrid correctly, but i cant get it to work with the multiselect.I tried doing something like the below code to get it to 'filter' using multiple selections.  I also set the Onfiltering tag for the datasource, but alas i get this error when selecting 2 fields "Cannot perform '=' operation on System.Int32 and System.String." &...

get DB size by using SQL
Hi, we are using SQL anywhere 10/11 how can we determine the DB Size for SQL anywhere? I found something similar for MSSQL & mySQL here: http://www.youdidwhatwithtsql.com/get-database-size-with-t-sql-and-mysql/414 can this be done with SQL anywhere 10/11? and specially with an extra filter, per table: WHERE multitenant_id = '12' //just an example You can get the file size of the main dbspace by doing a select db_property('filesize') or use select DB_EXTENDED_PROPERTY() for the file size of the additional files. The functions return the number of pages. Th...

How to add users to a SQL Server DB used for authentication using SQL query
Hi, I am looking for a simple way to add users manually to a SQL Server DB (set up using aspnet_regsql.exe) via a SQL query. What are the required values, that have to be set in the different tables? Thanks in advance, Markus By default SqlMembershipProvider calls the aspnet_Membership_CreateUser stored procedure to create a user, you can use T-SQL statment like sp_help aspnet_Membership_CreateUser to learn how to use it.Welcome to my SQL/ASPNET forum for Chinese http://51up.org/bbs/forumdisplay.php?fid=38...

Populating 2 listboxes from db using jscript
Hi, I need to populate 2 listboxes from a db. The first listbox should be populated once the page is loaded. The second listbox must be populated also from the db according to what the user selected in the first listbox. I want to use jscript to avoid postback. I am also not using ado.net but classic ado. All this is my boss's requirements although i tried to persuade him otherwise. also he wants to avoid datatables etc. I think that i need to use jscript arrays but i am not sure how to write the code. I am using vb.net/ Can someone please help me? Thanks Hi, This contro...

Web resources about - Multiselection Listbox to Populate SQL Db using C# - asp.net.getting-started

OnePlus releases Android Lollipop-based OxygenOS here's how to install OxygenOS on OnePlus One
... while using OTG features; inability to hang up a call using headphone controls; crashes while uploading files to the cloud; and no multiselection ...

The Finger on the Beatles
The Finger on Music The Beatles' Albums Singles Artist Title Cert. Date Label Award Description Level BEATLES, THE 1 3/8/2010 APPLE Multi Platinum ...

Wazapp for Nokia N9 gets major update. Bumped to version 0.9.12.
It has been long since we covered some Nokia N9 related news on our blog. But can’t resist reporting this. Wazapp the fruit of hard work put ...

WD My Cloud Mirror - WD Community
Forums &#8226 News & Announcements &#8226 Knowledge Base WD Community : Personal Cloud Storage : WD My Cloud Mirror Register · Sign In · Help ...

Ocenaudio 2.0.7
Ocenaudio is a full featured, fast and easy to use audio and music editor. It is the ideal software for people who need to edit and analyze audio ...

Ocenaudio 2.0.6
Ocenaudio is a full featured, fast and easy to use audio and music editor. It is the ideal software for people who need to edit and analyze audio ...

Resources last updated: 1/20/2016 5:09:28 PM