Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

ListBox Selected Value

Posted on 2012-12-28
19
Medium Priority
?
375 Views
Last Modified: 2013-01-03
Hello:

I have a listbox that when I select multiple values I want the values to go into a database. I do not get any error from the script blow but the values are not being inserted.

<asp:ListBox ID="MenuAccess" SelectionMode="Multiple" runat="server" />

Open in new window

if (MenuAccess.Items.Count > 0)
        {
            for (int i = 0; i < MenuAccess.Items.Count; i++)
            {
                if (MenuAccess.Items[i].Selected)
                {
                    SqlConnection conn;
                    SqlCommand comm;
                    string connectionString1 = ConfigurationManager.ConnectionStrings["DataString"].ConnectionString;
                    conn = new SqlConnection(connectionString1);
                    comm = new SqlCommand("INSERT INTO Menus (LinkID) VALUES (@LinkID)", conn);
                    comm.Parameters.Add("@LinkID", System.Data.SqlDbType.Int);
                    comm.Parameters["@LinkID"].Value = MenuAccess.Items[i].Text;
                }
                try
                {
                    conn.Open();
                    comm.ExecuteNonQuery();
                }
                finally
                {
                    conn.Close();
                }
            }
        }

Open in new window

0
Comment
Question by:RecipeDan
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 10
  • 8
19 Comments
 
LVL 41

Expert Comment

by:guru_sami
ID: 38728469
1: Set the breakpoints and debug to see if right value is assigned to the LinkID parameter
2: move try/finally inside if
3: Add catch block
4: If you have access to SqlProfiler then try to setup a trace and see if the command is executed and the value passed.
0
 
LVL 75

Expert Comment

by:käµfm³d 👽
ID: 38728479
Which method is the code you posted above contained within?
0
 
LVL 1

Author Comment

by:RecipeDan
ID: 38738432
It seems to be a null value. However, the listbox does have values when the Page is loaded

      <option value="13">Change Password</option>
      <option value="14">New User</option>
      <option value="15">Delete Users</option>
0
Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

 
LVL 41

Expert Comment

by:guru_sami
ID: 38738584
Make sure your ListBox is not re-binded during postback...
i.e. place your listbox binding code in this block...
if(!Page.IsPostBack)
{ //Bind listbox
}

Open in new window

Or share your code-behind on how you are binding the data to listbox.
0
 
LVL 1

Author Comment

by:RecipeDan
ID: 38740991
I made a few changes and it still does not work. Here is the current way I am binding the ListBox and trying to enter the values in a table.  

if (Page.IsPostBack == true)
        {
            string IsCurrent = Request.Form["PAns"];
            if (IsCurrent == "Y")
            {
                PAns.Visible = true;
                PYes.Visible = true;
                PNo.Visible = false;
                BindMenuAccessList();
            }
            else
            {
                PAns.Visible = true;
                PYes.Visible = false;
                PNo.Visible = true;
                BindMenuAccessList2();
            }
        }

Open in new window

protected void UserAdd_Click(object sender, EventArgs e)
    {
        if (MenuAccess.Items.Count > 0)
        {
            for (int i = 0; i < MenuAccess.Items.Count; i++)
            {
                if (MenuAccess.Items[i].Selected)
                {
                    SqlConnection conn1;
                    SqlCommand comm1;
                    string connectionString = ConfigurationManager.ConnectionStrings["DataString"].ConnectionString;
                    conn = new SqlConnection(connectionString);
                    comm = new SqlCommand("INSERT INTO ACC_Menus (LinkID) VALUES (@LinkID)", conn);
                    comm.Parameters.Add("@LinkID", System.Data.SqlDbType.Int);
                    comm.Parameters["@LinkID"].Value = MenuAccess.Items[i].Text;
                    try
                    {
                        conn.Open();
                        comm.ExecuteNonQuery();
                    }
                    finally
                    {
                        conn.Close();
                    }
                }
            }
        }
    }

Open in new window

0
 
LVL 41

Expert Comment

by:guru_sami
ID: 38741013
Why are you binding menulist on postback?
if (Page.IsPostBack == true)
0
 
LVL 1

Author Comment

by:RecipeDan
ID: 38741138
When I first started I was binding it on page load and it did not work.
0
 
LVL 1

Author Comment

by:RecipeDan
ID: 38741142
It binds fine. When I load the page, the names and values are shows in the Listbox.
0
 
LVL 41

Expert Comment

by:guru_sami
ID: 38741153
yes but when you rebind it on postback the selected values are lost...
so you mush put your code in
if(!Page.IsPostBack){ }
0
 
LVL 1

Author Comment

by:RecipeDan
ID: 38741438
Put what code in this: if(!Page.IsPostBack){ } ? BindMenuAccessList()?
0
 
LVL 41

Expert Comment

by:guru_sami
ID: 38741458
Yes... the code to bind your MenuAccess ListBox control
0
 
LVL 1

Author Comment

by:RecipeDan
ID: 38742003
That worked...however I am getting a different error Invalid Input string. It has to do with this line
comm.Parameters["@LinkID"].Value = MenuAccess.Items[i].Text;

Open in new window


When I hard code a value like this:
comm.Parameters["@LinkID"].Value = "3";

It works fine.
0
 
LVL 41

Expert Comment

by:guru_sami
ID: 38742068
Are you getting any empty string for the Text?
Try to cast the value to Int32 like:

comm.Parameters["@LinkID"].Value = Convert.ToInt32(MenuAccess.Items[i].Text);

Open in new window

0
 
LVL 1

Author Comment

by:RecipeDan
ID: 38742153
it is reading the first value and inserting it as many times I selected the values. So I select 5 items and the first value is 12. It is insertring the 12 five times into the table instead of 12, 7, 3, 6, 2
0
 
LVL 41

Expert Comment

by:guru_sami
ID: 38742190
When you debug and check the value on each loop do you see right value being assigned to the LinkID parameter or not?
if not..
Try using the ListItem while looping instead of an Items collection...like shown here: http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.listbox.aspx

foreach (ListItem li in ListBox1.Items)
          {
              if (li.Selected == true)
              {
                  msg += "<BR>" + li.Text + " is selected.";
              }
          }

Open in new window

0
 
LVL 1

Author Comment

by:RecipeDan
ID: 38742284
When I do that the text shows (LinkName) instead of the actual value (Link ID).

Change Password is selected.
List Users is selected.
New User is selected.
Update User is selected.
Delete User is selected.

It should be

12 is selected.
7 is selected.
5 is selected.
4 is selected.
2 is selected.
0
 
LVL 1

Author Comment

by:RecipeDan
ID: 38742286
Its binding right

            MenuAccess.DataValueField = "LinkID";
            MenuAccess.DataTextField = "LinkName";
            MenuAccess.DataBind();
            Menureader.Close();
0
 
LVL 41

Accepted Solution

by:
guru_sami earned 2000 total points
ID: 38742298
ok great...then you should be using the Value property instead of Text to pass as LinkId

msg += "<BR>" + li.Value+ " is selected.";
0
 
LVL 1

Author Closing Comment

by:RecipeDan
ID: 38742389
It works great. Thank you for your help.
0

Featured Post

Enroll in September's Course of the Month

This month’s featured course covers 16 hours of training in installation, management, and deployment of VMware vSphere virtualization environments. It's free for Premium Members, Team Accounts, and Qualified Experts!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

User art_snob (http://www.experts-exchange.com/M_6114203.html) encountered strange behavior of Android Web browser on his Mobile Web site. It took a while to find the true cause. It happens so, that the Android Web browser (at least up to OS ver. 2.…
Exception Handling is in the core of any application that is able to dignify its name. In this article, I'll guide you through the process of writing a DRY (Don't Repeat Yourself) Exception Handling mechanism, using Aspect Oriented Programming.
How to fix incompatible JVM issue while installing Eclipse While installing Eclipse in windows, got one error like above and unable to proceed with the installation. This video describes how to successfully install Eclipse. How to solve incompa…
Want to learn how to record your desktop screen without having to use an outside camera. Click on this video and learn how to use the cool google extension called "Screencastify"! Step 1: Open a new google tab Step 2: Go to the left hand upper corn…
Suggested Courses

704 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question