Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Populate a combobox with array information

I'm trying to populate a ComboBox with PART of an array that is in another class. I have to make an application that creates customers, inventory and orders. On the order form, I'm trying to pull the customer ID and inventory ID information from the arrays that are in the customer and inventory classes respectively. The arrays have multiple types of information in them: Customer ID, name, Address, state, zip, etc; Inventory ID, Name, discount value and price.

This is what my arrays are set up like:

public static Customer[] myCustArray = new Customer[100];

public string customerID;
public string customerName;
public string customerAddress;
public string customerState;
public int customerZip;
public int customerAge;
public int totalOrdered;

and this is what my comboboxes are sort of set up like:

public void custIDComboBox_SelectedIndexChanged(object sender, EventArgs e)
{
    custIDComboBox.Items.AddRange(Customer.myCustArray);

    custIDComboBox.DataSource = Customer.getAllCustomers();
}
like image 894
user1911789 Avatar asked Dec 18 '12 05:12

user1911789


2 Answers

Use data binding.

Giving an existing array of object (in your case "Customers") defined as such:

public static Customer[] myCustArray = new Customer[100];

Define the array as the data source like this:

BindingSource theBindingSource = new BindingSource();
theBindingSource.DataSource = myCustArray;
myComboBox.DataSource = bindingSource.DataSource;

Then you can set the lable and value of each item like this:

//That should be a string represeting the name of the customer object property.
myComboBox.DisplayMember = "customerName";
myComboBox.ValueMember = "customerID";

And that's it.

like image 76
Mortalus Avatar answered Nov 20 '22 12:11

Mortalus


Customer.myCustArray[0] = new Customer { customerID = "1", customerName = "Jane" };  
Customer.myCustArray[1] = new Customer { customerID = "2", customerName = "Jack" };

you won't need two lines above, I added them to see the output, the following code generates the ComboBox items:

foreach (Customer cus in Customer.myCustArray)
{
    comboBox1.Items.Add("[" + cus.customerID + "] " + cus.customerName);
}

you can copy this code to the appropriate event, for example it can be FormLoad, and if you want your ComboBox's items refresh every time your form activates you can do this:

private void Form3_Activated(object sender, EventArgs e)
{
    comboBox1.Items.Clear();
    foreach (Customer cus in Customer.myCustArray)
    {
        comboBox1.Items.Add("[" + cus.customerID + "] " + cus.customerName);
    }
}
like image 34
Mahdi Tahsildari Avatar answered Nov 20 '22 12:11

Mahdi Tahsildari