thanks for your help, I have a listbox where I am inserting a string, however when I select that new line I receive the following error: System.InvalidCastException: 'No se puede convertir un objeto de tipo 'System.String' al tipo 'TESTLSD.Registro'.' This is my code:
private void btnNuevoRegistro_Click(object sender, EventArgs e)
{
if (txtNuevoRegistro.Text.Length > 0)
{
lstLSD.Items.Insert(lstLSD.SelectedIndex 1, Convert.ToString(txtNuevoRegistro.Text));
txtNuevoRegistro.Clear();
}
else MessageBox.Show("No hay registro para adicionar");
}
And
this is my SelectedIndexChange
private void lstLSD_SelectedIndexChanged(object sender, EventArgs e)
{
if (this.lstLSD.SelectedIndex != -1)
{
registroSeleccionado = (Registro)this.lstLSD.SelectedItem;
label2.Text = "Registro " registroSeleccionado;
string item = lstLSD.SelectedItem.ToString();
if (item.StartsWith("01")) { button1.Enabled = true; } else { button1.Enabled = false; };
if (item.StartsWith("02")) { button3.Enabled = true; } else { button3.Enabled = false; };
if (item.StartsWith("03")) { button4.Enabled = true; } else { button4.Enabled = false; };
if (item.StartsWith("04")) { button5.Enabled = true; } else { button5.Enabled = false; };
}
}
Any idea so I can select this line after adding it? THANKS!
CodePudding user response:
I assume its this line thats failing
registroSeleccionado = (Registro)this.lstLSD.SelectedItem;
you are trying to cast a string to so you can assign it to registroSeleccionado which I assume is of type TESTLSD.Registro
You are trying to cast a string to it, that wont work. What is the relationship between that string and that class. If you had the class instance origially try setting the ListItem.Tag to that instance,