Improve company productivity with a Business Account.Sign Up

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 398
  • Last Modified:

ListBox Selected Value

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
RecipeDan
Asked:
RecipeDan
  • 10
  • 8
1 Solution
 
guru_samiCommented:
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
 
käµfm³d 👽Commented:
Which method is the code you posted above contained within?
0
 
RecipeDanAuthor Commented:
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
Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

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.

 
guru_samiCommented:
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
 
RecipeDanAuthor Commented:
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
 
guru_samiCommented:
Why are you binding menulist on postback?
if (Page.IsPostBack == true)
0
 
RecipeDanAuthor Commented:
When I first started I was binding it on page load and it did not work.
0
 
RecipeDanAuthor Commented:
It binds fine. When I load the page, the names and values are shows in the Listbox.
0
 
guru_samiCommented:
yes but when you rebind it on postback the selected values are lost...
so you mush put your code in
if(!Page.IsPostBack){ }
0
 
RecipeDanAuthor Commented:
Put what code in this: if(!Page.IsPostBack){ } ? BindMenuAccessList()?
0
 
guru_samiCommented:
Yes... the code to bind your MenuAccess ListBox control
0
 
RecipeDanAuthor Commented:
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
 
guru_samiCommented:
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
 
RecipeDanAuthor Commented:
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
 
guru_samiCommented:
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
 
RecipeDanAuthor Commented:
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
 
RecipeDanAuthor Commented:
Its binding right

            MenuAccess.DataValueField = "LinkID";
            MenuAccess.DataTextField = "LinkName";
            MenuAccess.DataBind();
            Menureader.Close();
0
 
guru_samiCommented:
ok great...then you should be using the Value property instead of Text to pass as LinkId

msg += "<BR>" + li.Value+ " is selected.";
0
 
RecipeDanAuthor Commented:
It works great. Thank you for your help.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

  • 10
  • 8
Tackle projects and never again get stuck behind a technical roadblock.
Join Now