Websteoj01
Websteoj01

Reputation: 3

Edit Items in a ListBox

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

Upvotes: 0

Views: 18178

Answers (2)

Reinaldo
Reinaldo

Reputation: 4666

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!

Upvotes: 1

john sky
john sky

Reputation: 21

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

Upvotes: 0

Related Questions