Adding listview items to dynamically created groups

Hi,
i want to add a group to a listview from inside the message loop. Then i want to add a new item to this group. But this fails in the first attempt that is made (because the AddItem Method returns -1) but works at the second time (index is now > -1).

Problems happening from line 38 on (var addedIndex = listview.AddItem("New Name", "New Data", groupIndex); )

Addgroup test.dcf (4.8 KB)

function OnClick(clickData)
{
	var dlg = clickData.func.Dlg;
	dlg.template = "dialog1";
	dlg.detach = true;
	dlg.Create();

	var listview = dlg.Control("listview");
	var groups = ["Dates", "Sepcial"];
	for(var i = 0; i < groups.length; i++)
	{
		var group = groups[i];
		var createdGroup = listview.AddGroup(group, i); //this is working
		listview.AddItem("Sample " + group, i, i);
	}
	listview.EnableGroupView(true);
	listview.columns.AutoSize();
	

	while (true) 
	{
		var msg = dlg.GetMsg();
        if (!msg.result) 
			break;
			
		if(msg.event == "click" && msg.control == "buttonAdd" )
		{
			var newGroup = "New Group";

			var groupIndex = ArrayIndexOf(groups, newGroup);
			Log("Groupindex: " + groupIndex);
			if(groupIndex == -1)
			{
				groupIndex = listview.AddGroup(newGroup, groups.length+1);
				Log("Groupindex was -1. New Groupindex is " + groupIndex);
			}
			
			var addedIndex = listview.AddItem("New Name", "New Data", groupIndex);
			Log("Added item index is " + addedIndex);

			if(addedIndex > -1) //this is necessary since i cannot be sure that it is added
			{
				Log("Added index is now valid: " + addedIndex);
				
				var lvItem = listview.GetItemAt(addedIndex);
				lvItem.subitems(0) = true ? "Yes" : "No";
		
				listview.columns.AutoSize();
			}
		}
	}
}

function ArrayIndexOf(array, element)
{
	for(var i = 0; i < array.length; i++)
		if(array[i] == element)
			return i;

	return -1;
}

function Log(msg) { DOpus.Output(String(msg)); }

Clicking the button produces the following log for me

Groupindex: -1
Groupindex was -1. New Groupindex is 2
Added item index is -1
Groupindex: -1
Groupindex was -1. New Groupindex is 3
Added item index is 2
Added index is now valid: 2

Sorry. My fault, late night coding

groupIndex = listview.AddGroup(newGroup, groups.length+1);

Messed up with indexes here. Should be


groupIndex = listview.AddGroup(newGroup, groups.length); //+ 1 removed