0
votes

I am creating a program using WinForms so users can input info into textboxes on one form which then are saved into a Listbox on another form. I would like to be able to edit the items saved in the listbox by opening the original form on a button click. Really struggling with it as I can't think of the code and I can't seem to find a solution. My Code:

private void btnAdd_Click(object sender, EventArgs e)
    {
        RoomDisplayForm newRoomDisplayForm = new RoomDisplayForm();
        newRoomDisplayForm.ShowDialog();
        if(newRoomDisplayForm.DialogResult == DialogResult.OK)
        {
            listBoxRooms.Items.Add(newRoomDisplayForm.value);
        }
        newRoomDisplayForm.Close();
    }

    private void btnRemove_Click(object sender, EventArgs e)
    {
        this.listBoxRooms.Items.RemoveAt(this.listBoxRooms.SelectedIndex);
    }

    private void btnEdit_Click(object sender, EventArgs e)
    {

    }

So i've got a Add and Remove button which work perfectly just need a solution to the edit button.

Thanks in advance

2
Since you are able to remove an item using the selected index, have you tried using the same to get the selected list item? Assuming RoomDisplayForm.value contains all the information you need, you should be able to use the returned object to then populate the form? - Ciara

2 Answers

1
votes

I'm guessing newRoomDisplayForm.value is a property or a public member inside the form. You just need to do something like this:

private void btnEdit_Click(object sender, EventArgs e)
{
   if(listBoxRooms.SelectedIndex < 0) return;

   var tmpValue = listBoxRooms.Items[listBoxRooms.SelectedIndex].ToString();
   RoomDisplayForm newRoomDisplayForm = new RoomDisplayForm();
   newRoomDisplayForm.value = tmpValue;
   newRoomDisplayForm.ShowDialog();

   //TODO: inside "newRoomDisplayForm" set the value to the textbox
   // ie.: myValueTextBox.Text = this.value;

   if(newRoomDisplayForm.DialogResult == DialogResult.OK)
   {
      // replace the selected item with the new value
      listBoxRooms.Items[listBoxRooms.SelectedIndex] = newRoomDisplayForm.value;
   }
}

Hope it helps!

0
votes

You can simply remove the listitem in that specific position, create a new item and add it again. it's kind of replacement.