I am new in C# OOP. I have a simple form including a textbox, a listbox and a button to add the input string of the textbox to the listbox. I want to create a Car object using the textbox info (model and price) and add it to the listbox. My question is: What is the difference between these two solutions? 1- add items using the Items.Add() method of the listbox (much simpler) 2- add items using a bindingsource instance and assign it to listbox DataSource property.
Here are the codes:
1:
namespace CarShopGUI
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void groupBox1_Enter(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
Car c = new Car(txt_Model.Text,decimal.Parse(txt_Price.Text));
lst_inventory.Items.Add(c);
}
private void Form1_Load(object sender, EventArgs e)
{
}
}
}
2:
namespace CarShopGUI
{
public partial class Form1 : Form
{
Store myStore = new Store();
BindingSource carInventoryBindingSource = new BindingSource();
public Form1()
{
InitializeComponent();
}
private void groupBox1_Enter(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
Car c = new Car(txt_Model.Text,decimal.Parse(txt_Price.Text));
myStore.CarList.Add(c);
carInventoryBindingSource.ResetBindings(false);
}
private void Form1_Load(object sender, EventArgs e)
{
carInventoryBindingSource.DataSource = myStore.CarList;
lst_inventory.DataSource = carInventoryBindingSource;
}
}
}
In the first example where you add an item to a ListBox
, the list is entirely "owned" by that UI control. If you wanted to perform other operations on that list like adding or removing items or doing something with that list of items, you'd have to get it from the ListBox
. Then, if you modified the list, you'd have to either make corresponding changes to the items in the ListBox
or just clear it and add the items back to it.
In the second example you're binding to a List<Car>
. That list "owns" its contents. If you wanted to do some operations with those cars, you could just pass that list to another method, and after it's modified you can reset the bindings to update the control. Or if the underlying data source changes you can load it into that List
and reset the bindings.
ListBox
is not strongly typed. You can add any object to it. A List<Car>
will contain only items of type Car
.
If all you want to do is display items on the screen so that users can see them and pick one then just adding directly to the ListBox
may be sufficient. But if that list reflects a data source that changes then keeping that source separate and binding it to the control is probably better.