Solved

ListBox Selected Value

Posted on 2012-12-28
19
362 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
  • 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
Active Directory Webinar

We all know we need to protect and secure our privileges, but where to start? Join Experts Exchange and ManageEngine on Tuesday, April 11, 2017 10:00 AM PDT to learn how to track and secure privileged users in Active Directory.

 
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 500 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

Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

Just a quick little trick I learned recently.  Now that I'm using jQuery with abandon in my asp.net applications, I have grown tired of the following syntax:      (CODE) I suppose it just offends my sense of decency to put inline VBScript on a…
This article is for Object-Oriented Programming (OOP) beginners. An Interface contains declarations of events, indexers, methods and/or properties. Any class which implements the Interface should provide the concrete implementation for each Inter…
This video shows how to use Hyena, from SystemTools Software, to bulk import 100 user accounts from an external text file. View in 1080p for best video quality.

828 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