3
votes

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;
3
In Button2Click(), swap the order of the lines. And then try to figure out why it did not work with the present code.Tom Brunberg
@TomBrunberg is correct. You would do better to record the indexes of the items you want to delete before you attempt to delete either of them. and then do the deletions by index.MartynA
@TomBrunberg oops! kiddish mistake. Thank You.bear

3 Answers

4
votes

A safe(r) way to do the deletions is

procedure TForm1.DeleteItems(const TextToFind : String);
var
  i1,
  i2 : Integer;
begin
  i1 := ListBox1.Items.IndexOf(TextToFind);  
  i2 := ComboBox1.Items.IndexOf(TextToFind);
  if i1 >=0 then
    ListBox1.Items.Delete(i1);
  if i2 >=0 then
    ComboBox1.Items.Delete(i2);
end;

Usage:

DeleteItems(Edit1.Text);

because this does not make assumptions about which items are selected in the two lists.

I leave you to find out using the debugger why you are getting the AV. It will be more instructive for you to find out than me to tell you.

1
votes

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
0
votes
procedure TMainForm.Button2Click(Sender: TObject);
begin
  if ListBox1.Selected.Index > -1 then ListBox1.Items.Delete(ListBox1.Selected.Index);
  if ComboBox1.ItemIndex > - 1 then ComboBox1.Items.Delete(ComboBox1.ItemIndex);
end;