When I insert a second Object(a Child), I need to assign to his parent the name of his child (having already the Child object, that has the parents name in a property), but when I call the Parent object always returns the child object.
I'm using a Hashtable to store "Cargo" objects.
// Hashtable(key,value)
TablaCargos(CargoObject.Name, CargoObject)
And every Cargo should have a Parent and a Child list
Part of my class Cargo
class Cargo {
private string nombre;
private string codigo;
private string padre;
private List<string> hijos = new List<string>();
public Cargo() {
nombre = "";
codigo = "";
padre = "";
hijos = new List<string>();
}
//getter and setters
}
My form
Cargo cargo = new Cargo();
Cargo cargoHijo = new Cargo();
Cargo cargoPadre = new Cargo();
Hashtable TablaCargos = new Hashtable();
string Root = "";
private void btnAgregar_Click(object sender, EventArgs e)
{
cargo.Nombre = txtNombre.Text;
cargo.Codigo = txtCodigo.Text;
cargo.Padre = txtPadre.Text;
TablaCargos.Add(txtNombre.Text, cargo);
Ordenamiento(txtNombre.Text);
}
private void Ordenamiento(string cargoActual) {
cargoHijo = (Cargo)TablaCargos[cargoActual];
if (cargoHijo.Padre == "") {
// THIS IS A PARENT
Root = cargoActual;
} else {
// THIS IS A CHILD
AsignarPadre(cargoHijo.Padre, cargoHijo.Nombre);
}
private void AsignarPadre(String Padre, String Hijo)
{
// THE PROBLEM IS HERE, CLEARLY I SEND THE Parent's KEY
cargoPadre = (Cargo)TablaCargos[Padre];
// BUT IN THE NEXT LINE cargoPadre TAKES THE VALUE OF THE CHILD
// THE SAME VALUE OF cargoHijo
cargoPadre.Hijos.Add(Hijo);
}
I expect to assign the child's name to the parent's child property, but the child takes it.
Maybe I miss an instantiation or, I don't know
The problem was solved with this line cargo = new Cargo();
at the beginning btnAdicionar_Click
.
Thank you all for your time and advice. :)