0

I have two list boxes, listbox1 (customer id) and list box 2 customer emails, I need to link the items together to add the email to a SQL table based on the ID matching.

So line 1 in list 1 is linked to line 1 in listbox 2 , and so on ,

I'm not sure how to write the code for this, I thought I might need some sort of an array but I'm new to coding so I'm not to sure.

Any help would be fantastic

Cheers

4

3 回答 3

0

If I have got it right you probably want to get the values from each listbox in an iteration like:

private void InsertEntries()
        {
            int itemsCount = listBox1.Items.Count > listBox1.Items.Count ?
                listBox1.Items.Count :
                listBox2.Items.Count;

            for (int i = 0; i < itemsCount; i++)
            {
                string id = listBox1.Items[i].ToString();
                string email = listBox2.Items[i].ToString();

                //Do your work here
            }
        }

I believe though that you wouldn't need two listboxes to achieve this.

于 2013-07-17T13:26:08.503 回答
0

Based only on what you posted with no code etc and me not having much better to do I have written some code. Lets assume Entity Framework for your data access and you are selecting from a list of potential email addresses to update a selected customers email address. OR you are selecting from 2 lists to create a new customer.

I would also add the 2 listbox idea sounds weird and maybe needs a rethink, but without clarification here is some code which includes a method for updating and a method for adding customers. Also a customer class for passing to those methods.

void Main()    
{
    var customer = new Customer
      {
        CustomerId = Listbox1.SelectedValue,
        EmailAddress = Listbox2.SelectedValue
      };

    UpdateEmailAddress(customer);
    //OR
    AddCustomer(customer);

}

public void AddCustomer(Customer customer)
{
    using (var db = new DatabaseEntities())
    {
        db.Customers.Add(customer);
        db.SaveChanges();
    }
}

public void UpdateEmailAddress(Customer customer)
{
    using (var db = new DatabaseEntities())
    {
       var selectedCustomer = db.Customers.Where(x=>x.CustomerId==customer.CustomerId).Select(x=x);
       selectedCustomer.EmailAddress = customer.EmailAddress;
       db.SaveChanges();
    }
}

public class Customer
{
    public int CustomerId {get;set;}
    public string EmailAddress {get;set;}
}
于 2013-07-17T13:31:07.267 回答
0

you can use selected index of the list box for matching the id's in the first list box to the id's of the second list box,

That may be in the format as below

ListBox1.SelectedIndex matching this to ListBox2.SelectedIndex

Now you can opt the code to store in database.

于 2013-07-17T14:02:59.237 回答