How do I add a new item
from a TextBox and Button on a Windows Form at the end of an ArrayList
which references a class?
private product[] value = new product[4];
value[1] = new product("One",5)
value[2] = new product("Two",3)
value[3] = new product("Three",8)
textbox1
, textbox2
, textbox3
When I click Add
the new product gets added to the array:
value[1] = new product("One",5)
value[2] = new product("Two",3)
value[3] = new product("Three",8)
value[4] = new product("Four",2)
What is the code for doing this?
An array is a contiguous block of memory and if you want to append an element, you have to write it to the position following the last occupied position, provided the array is large enough.
C++ arrays aren't extendable. You either need to make the original array larger and maintain the number of valid elements in a separate variable, or create a new (larger) array and copy the old contents, followed by the element(s) you want to add.
C arrays don't have an end marker. It is your responsibility as the programmer to keep track of the allocated size of the array to make sure you don't try to access element outside the allocated size. If you do access an element outside the allocated size, the result is undefined behaviour.
Arrays are fixed size, which means you can't add more elements than the number allocated at creation time, if you need a auto sizing collection you could use List<T>
or an ArrayList
Example:
// using collection initializers to add two products at creation time
List<Product> products = new List<Product>{new Product("One",5), new Product("Two",3) };
// then add more elements as needed
products.Add(new Product("Three",8));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With