Solved

ListBox Selected Value

Posted on 2012-12-28
19
363 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
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
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

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

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

A quick way to get a menu to work on our website, is using the Menu control and assign it to a web.sitemap using SiteMapDataSource. Example of web.sitemap file: (CODE) Sample code to add to the page menu: (CODE) Running the application, we wi…
Real-time is more about the business, not the technology. In day-to-day life, to make real-time decisions like buying or investing, business needs the latest information(e.g. Gold Rate/Stock Rate). Unlike traditional days, you need not wait for a fe…
Finds all prime numbers in a range requested and places them in a public primes() array. I've demostrated a template size of 30 (2 * 3 * 5) but larger templates can be built such 210  (2 * 3 * 5 * 7) or 2310  (2 * 3 * 5 * 7 * 11). The larger templa…

756 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