Search code examples
delphifiremonkey

TComboBox and TListBox item Removal?


i am trying to add items to TListBox and TComboBox from text given in TEdit My code is working fine while adding item in TListBox TComboBox but when i try to remove the selected item in TListBox from itself and from TComobBox it shows Access Violation.

Below is procedure from my code:-

procedure TMainForm.Button1Click(Sender: TObject);
begin
  ListBox1.Items.Add(Edit1.Text);   
  ComboBox1.Items.Add(Edit1.Text);
end;

procedure TMainForm.Button2Click(Sender: TObject);
begin
  ListBox1.Items.Delete(ListBox1.Selected.Index);
  ComboBox1.Items.Delete(ComboBox1.Items.IndexOf(ListBox1.Selected.Text));
end;

Solved: Did a Kiddish Mistake now Solved. Here it is working code:

procedure TMainForm.Button2Click(Sender: TObject);
begin
  ComboBox1.Items.Delete(ComboBox1.Items.IndexOf(ListBox1.Selected.Text));
  ListBox1.Items.Delete(ListBox1.Selected.Index);      
end;

Solution

  • This line removes the item from the listbox

    ListBox1.Items.Delete(ListBox1.Selected.Index);
    

    This line is trying to remove the item from the combobox

    ComboBox1.Items.Delete(ComboBox1.Items.IndexOf(ListBox1.Selected.Text));
    

    But in it you refer to ListBox1.Selected.Text. This is referring the item you just removed in the first delete. Swapping the order of execution around should work:

    begin
      ComboBox1.Items.Delete(ComboBox1.Items.IndexOf(ListBox1.Selected.Text));
      ListBox1.Items.Delete(ListBox1.Selected.Index);
    end