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;
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With