我在列表视图中有一些列表我想防止添加已经存在的项目并且只允许不存在的项目我在发布我的问题之前搜索我找到一些删除重复项目的代码但这不是我的观点,一点点例如,试图实现目标的例子
listview1.Items.Add.caption := 'item1'
listview1.Items.Add.subitems.add:= 'content'
listview1.Items.Add.caption := 'item2'
listview1.Items.Add.subitems.add:= 'content2'
listview1.Items.Add.caption := 'item3'
listview1.Items.Add.subitems.add:= 'content3'
//duplicated line
listview1.Items.Add.caption := 'item1'// here what i want to ignore if exist and add any other items comes below
listview1.Items.Add.subitems.add:= 'content'
listview1.Items.Add.caption := 'item4'
listview1.Items.Add.subitems.add:= 'content4'
Run Code Online (Sandbox Code Playgroud)
关于如何实现忽略现有项目并添加其他项目的任何想法?
目前的代码
if Command = 'CallThis' then
begin
if Assigned(MS) then
begin
SL := TStringList.Create;
try
SL.LoadFromStream(MS);
for I := 0 to SL.Count -1 do
begin
Line := SL.Strings[I];
ExplodeLine(Line, item, content, num);
with vieform.list.Items.Add do
begin
Caption := StripHTML(item);
Subitems.Add(content);
Subitems.Add(num)
end;
end;
finally
SL.Free;
end;
MS.Free;
end;
end;
Run Code Online (Sandbox Code Playgroud)
您不应使用可视控件来存储和管理数据.拥有所有数据的列表,并在列表视图或您喜欢的任何其他控件中显示数据.
// class to store data (shortend)
TMyData = class
constructor Create( const Item, Content : string );
property Item : string;
property Content : string;
end;
// list to organize the data
MyList := TObjectList<TMyData>.Create(
// comparer, tell the list, when are items equal
TComparer<TMyData>.Construct(
function ( const L, R : TMyData ) : integer
begin
Result := CompareStr( L.Item, R.Item );
end ) );
// create an item
MyData := TMyData.Create( 'item1', 'content1' );
// check for duplicate in list
if not MyList.Contains( MyData ) then
MyList.Add( MyData )
else
MyData.Free;
// present the list in a ListView
ListView1.Clear;
for MyData in MyList do
begin
ListItem := ListView1.Items.Add;
ListItem.Data := MyData; // store a reference to the data item
ListItem.Caption := MyData.Item;
ListItem.SubItems.Add( MyData.Content );
end;
Run Code Online (Sandbox Code Playgroud)
就这样