从文本框向列表框添加字符串

Adding a string to a listbox from textbox

感谢您的帮助,我有一个列表框,我要在其中插入一个字符串,但是当我 select 那个新行时,我收到以下错误: System.InvalidCastException:'No se puede convertir un objeto de tipo 'System.String' al tipo 'TESTLSD.Registro'。 这是我的代码:

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 

这是我的 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; };
       }
  }

添加后我可以 select 知道这一行吗?谢谢!

我假设这行失败了

registroSeleccionado = (Registro)this.lstLSD.SelectedItem;

您正在尝试将字符串转换为,以便您可以将其分配给我认为类型为 TESTLSD.Registro

的 registroSeleccionado

您正在尝试将字符串转换为它,但这是行不通的。那个字符串和那个class有什么关系。如果您最初有 class 实例,请尝试将 ListItem.Tag 设置为该实例,