listbox multiple items

  • (2 Pages)
  • +
  • 1
  • 2

17 Replies - 5140 Views - Last Post: 06 July 2010 - 05:02 AM Rate Topic: -----

#1 megglz  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 11
  • View blog
  • Posts: 414
  • Joined: 22-August 08

listbox multiple items

Posted 01 July 2010 - 06:45 AM

I want to add multiple selected items into an array and then insert each item separately into the database.. Would the following be almost correct?


using (SqlConnection conn = new SqlConnection(connectionString))
{
using (SqlCommand sqlCommand1 = conn.CreateCommand())
    {
object[] o = new object[listBox1.Items.Count];
foreach(object o in listBox1.Items)
 string insertActivities = string.Format("INSERT into DATA (ID, ActivityName) VALUES ({0}, o)", DropDownList_EmployID.SelectedValue,);
   sqlCommand1.CommandText = insertActivities;
   sqlCommand1.CommandType = CommandType.Text;
   conn.Open();
   sqlCommand1.ExecuteNonQuery();
    conn.Close();
                }

            }




Is This A Good Question/Topic? 0
  • +

Replies To: listbox multiple items

#2 Curtis Rutland  Icon User is online

  • (╯□)╯︵ (~ .o.)~
  • member icon


Reputation: 4479
  • View blog
  • Posts: 7,801
  • Joined: 08-June 10

Re: listbox multiple items

Posted 01 July 2010 - 07:06 AM

First, I would use parameters rather than string building. String building leaves you open to SQL Injection attacks. Parameters escape input.

Second, what does your object array here do? You declare it but never use it. And then you enter the foreach loop, and declare another variable, this time just a plain object, with the same name. That shouldn't even work.

Third, what does your foreach loop do? You never use the object o variable. You use the string "o", but that's always going to be "o" no matter what

This post has been edited by insertAlias: 01 July 2010 - 07:07 AM

Was This Post Helpful? 0
  • +
  • -

#3 eclipsed4utoo  Icon User is offline

  • Not Your Ordinary Programmer
  • member icon

Reputation: 1524
  • View blog
  • Posts: 5,960
  • Joined: 21-March 08

Re: listbox multiple items

Posted 01 July 2010 - 07:16 AM

View PostinsertAlias, on 01 July 2010 - 09:06 AM, said:

First, I would use parameters rather than string building. String building leaves you open to SQL Injection attacks. Parameters escape input.

Second, what does your object array here do? You declare it but never use it. And then you enter the foreach loop, and declare another variable, this time just a plain object, with the same name. That shouldn't even work.

Third, what does your foreach loop do? You never use the object o variable. You use the string "o", but that's always going to be "o" no matter what


I think she is using the "object o" in the foreach simply as a way to loop through the items in the ListBox. She doesn't have to worry about invalid casting since it will cast to an "object".

IrishGirl, are you running into an issue? The code would seem to work.
Was This Post Helpful? 0
  • +
  • -

#4 FlashM  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 382
  • View blog
  • Posts: 1,195
  • Joined: 03-December 09

Re: listbox multiple items

Posted 01 July 2010 - 07:20 AM

Something like that:

public partial class Form1 : Form
{

    IList<User> users = new List<User>();

    public Form1()
    {
        InitializeComponent();
        PrepareTestData();
    }

    private void PrepareTestData()
    {
        User u1 = new User { Id = 1, ActivityName = "Activity 1" };
        User u2 = new User { Id = 2, ActivityName = "Activity 2" };
        User u3 = new User { Id = 3, ActivityName = "Activity 3" };

        users.Add(u1);
        users.Add(u2);
        users.Add(u3);

        usersListBox.DataSource = users;
        usersListBox.DisplayMember = "ActivityName";
        usersListBox.ValueMember = "Id";
    }

    private void btnInsertSelected_Click(object sender, EventArgs e)
    {
        ListBox.SelectedObjectCollection selection = usersListBox.SelectedItems;

        foreach (User user in selection)
        {
            //Database insert logic here...
        }
    }
}

class User
{
    public int Id { get; set; }
    public string ActivityName { get; set; }
}


Was This Post Helpful? 0
  • +
  • -

#5 Curtis Rutland  Icon User is online

  • (╯□)╯︵ (~ .o.)~
  • member icon


Reputation: 4479
  • View blog
  • Posts: 7,801
  • Joined: 08-June 10

Re: listbox multiple items

Posted 01 July 2010 - 07:29 AM

View Posteclipsed4utoo, on 01 July 2010 - 06:16 AM, said:

View PostinsertAlias, on 01 July 2010 - 09:06 AM, said:

First, I would use parameters rather than string building. String building leaves you open to SQL Injection attacks. Parameters escape input.

Second, what does your object array here do? You declare it but never use it. And then you enter the foreach loop, and declare another variable, this time just a plain object, with the same name. That shouldn't even work.

Third, what does your foreach loop do? You never use the object o variable. You use the string "o", but that's always going to be "o" no matter what


I think she is using the "object o" in the foreach simply as a way to loop through the items in the ListBox. She doesn't have to worry about invalid casting since it will cast to an "object".

IrishGirl, are you running into an issue? The code would seem to work.


See, I don't think it will. Look at this line closely:
string insertActivities = string.Format("INSERT into DATA (ID, ActivityName) VALUES ({0}, o)", DropDownList_EmployID.SelectedValue,);


It's not using the value of object o, it's using the literal string "o". So every insert would be "o". The first parameter is coming from a different control altogether, what I'm assuming is an employee id selector.

OP would need to rewrite it more like this:
string insertActivities = "INSERT into DATA (ID, ActivityName) VALUES (@ID, @ActivityName)";
sqlCommand1.CommandText = insertActivities;
sqlCommand1.Parameters.AddWithValue("@ID", DropDownList_EmployID.SelectedValue);
sqlCommand1.Parameters.AddWithValue("@ActivityName", o);


Also, to irishgirl:
Some database advice. If those are all the fields in your table, I would suggest adding a row id field. Something like an auto-increment integer field to be your primary key. It is very much worth doing.

This post has been edited by insertAlias: 01 July 2010 - 07:31 AM

Was This Post Helpful? 1
  • +
  • -

#6 megglz  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 11
  • View blog
  • Posts: 414
  • Joined: 22-August 08

Re: listbox multiple items

Posted 01 July 2010 - 08:18 AM

Thanks all, sorry I never had time to run the code yet as I had to leave desk unexpectedly. Will try now.
Was This Post Helpful? 0
  • +
  • -

#7 megglz  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 11
  • View blog
  • Posts: 414
  • Joined: 22-August 08

Re: listbox multiple items

Posted 01 July 2010 - 08:24 AM

Quote

A local variable named 'o' cannot be declared in this scope because it would give a different meaning to 'o', which is already used in a 'parent or current' scope to denote something else

Was This Post Helpful? 0
  • +
  • -

#8 megglz  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 11
  • View blog
  • Posts: 414
  • Joined: 22-August 08

Re: listbox multiple items

Posted 01 July 2010 - 08:38 AM

Hi, this code compiles fine now but there is a problem with the SQL issue maybe as it doesnt bind to the gridview (its blank) and doesnt insert into the db. I wont be able to check this again until Monday as I will be off until then. Thanks again for all your help, I would truly be lost without this place :)

using (SqlConnection conn = new SqlConnection(connectionString))
{
    using (SqlCommand sqlCommand1 = conn.CreateCommand())
    {
        // object[] o = new object[ListBox_Activities.Items.Count];
        foreach (object o in ListBox_Activities.SelectedValue)
        {
            string insertActivities = string.Format("INSERT into Data (ID, ActivityName) VALUES (@ID, @ActivityName)");
            sqlCommand1.CommandText = insertActivities;
            sqlCommand1.Parameters.AddWithValue("@ID", DropDownList_Employees.SelectedValue);
            sqlCommand1.Parameters.AddWithValue("@ActivityName", o);
            sqlCommand1.CommandType = CommandType.Text;
            conn.Open();
            sqlCommand1.ExecuteNonQuery();
            conn.Close();
        }
    }
}

GridView_ABC.DataBind();
GridView_Team.Visible = false;


This post has been edited by eclipsed4utoo: 01 July 2010 - 11:48 AM
Reason for edit:: fixed code formatting

Was This Post Helpful? 0
  • +
  • -

#9 eclipsed4utoo  Icon User is offline

  • Not Your Ordinary Programmer
  • member icon

Reputation: 1524
  • View blog
  • Posts: 5,960
  • Joined: 21-March 08

Re: listbox multiple items

Posted 01 July 2010 - 11:46 AM

You are not setting the DataSource of the GridView. You are calling DataBind but nothing is there to databind. No datasource means no data.
Was This Post Helpful? 0
  • +
  • -

#10 megglz  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 11
  • View blog
  • Posts: 414
  • Joined: 22-August 08

Re: listbox multiple items

Posted 05 July 2010 - 12:42 AM

I thought it was that too, but when I'm debugging it steps on to this line

 foreach(object o in ListBox_Activities.SelectedValue) {



and then completely skips the block of code there, this is why it's showing blank and not inserting hmmm.
Was This Post Helpful? 0
  • +
  • -

#11 Curtis Rutland  Icon User is online

  • (╯□)╯︵ (~ .o.)~
  • member icon


Reputation: 4479
  • View blog
  • Posts: 7,801
  • Joined: 08-June 10

Re: listbox multiple items

Posted 05 July 2010 - 12:50 AM

View Postirishgirl, on 05 July 2010 - 06:42 AM, said:

I thought it was that too, but when I'm debugging it steps on to this line

 foreach(object o in ListBox_Activities.SelectedValue) {



and then completely skips the block of code there, this is why it's showing blank and not inserting hmmm.


SelectedValue isn't a collection. It's a single object.
Was This Post Helpful? 1
  • +
  • -

#12 megglz  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 11
  • View blog
  • Posts: 414
  • Joined: 22-August 08

Re: listbox multiple items

Posted 05 July 2010 - 01:01 AM

Yes, I understand this now. I got the code working with
foreach (ListItem li in ListBox_Activities.Items) 



but this obviously entered every entry into the db, not just the several selected ones. How can I do it for the several selected? If I try as

 foreach (object o in ListBox_Activities.SelectedValue)



It passes through blanks.

This post has been edited by irishgirl: 05 July 2010 - 01:08 AM

Was This Post Helpful? 0
  • +
  • -

#13 megglz  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 11
  • View blog
  • Posts: 414
  • Joined: 22-August 08

Re: listbox multiple items

Posted 05 July 2010 - 01:16 AM

I found that i could do an 'if statement' to see if the value has been selected. However, it does not pick up on any selected values :s

     foreach (ListItem li in ListBox_Activities.Items) {
            if (li.Selected)
            {
//
            }
      }


Was This Post Helpful? 0
  • +
  • -

#14 Curtis Rutland  Icon User is online

  • (╯□)╯︵ (~ .o.)~
  • member icon


Reputation: 4479
  • View blog
  • Posts: 7,801
  • Joined: 08-June 10

Re: listbox multiple items

Posted 05 July 2010 - 01:23 AM

Try using .SelectedItems. You might have to cast them.

This post has been edited by insertAlias: 05 July 2010 - 01:25 AM

Was This Post Helpful? 0
  • +
  • -

#15 megglz  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 11
  • View blog
  • Posts: 414
  • Joined: 22-August 08

Re: listbox multiple items

Posted 05 July 2010 - 01:32 AM

That property does not work for me, no matter what i try. i can only do SelectedItem. Do you have an example?
Was This Post Helpful? 0
  • +
  • -

  • (2 Pages)
  • +
  • 1
  • 2