简体   繁体   中英

Change sorting of StringCollection

On my current project the user can create a control that gets docked in a TableLayoutPanel. The controls name gets saved in a StringCollection and on every start of the program the controls get recreated. I would like to implement a feature that allows the user to change the order of the controls. The moving part is working, the problem is that next time the program gets started, the controls get recreated in the old order because they get created from the StringCollection. That means to change the order of the controls and keep that for the future i would have to change the sorting of the StringCollection. Is there any way to do that? And if yes, how would i go about that?

Currently i would move the control up with this code from a context menu:

if (this.Parent == null)
    return;

var index = this.Parent.Controls.GetChildIndex(this);
if (index <= this.Parent.Controls.Count)
    this.Parent.Controls.SetChildIndex(this, index - 1);

and obv. move it down with +1 instead. In the loading event i just go through the StringCollection with foreach and create the controls.

foreach (string line in Properties.Settings.Default.MessageStringCollection)
{
    if (!String.IsNullOrEmpty(line))
    {
        createNewMessageButton(line);
    }
}

I have not worked with properties yet, but why not creating a custom properties type eg "SortedControlsList". You could check out an implementation suggestion on codeproject

Sometimes i should either not try so solve problems if i'm too tired or just not create questions without sleeping or spending more time on thinking about a solution. I was able to solve the problem on my own, the solution is pretty easy if i just try to use what i'm already using for the normal sorting and changing that to the StringCollection.

var SCindex = Properties.Settings.Default.MessageStringCollection.IndexOf(Message);
if (SCindex > 0)
{
    Properties.Settings.Default.MessageStringCollection.Remove(String.Format("{0}", Message));
    Properties.Settings.Default.MessageStringCollection.Insert(SCindex - 1, Message);
    Properties.Settings.Default.Save();
}

You'll need to update your property for it to remain the way you want it to on the next startup.

see: https://msdn.microsoft.com/en-us/library/xb5dd1f1(v=vs.110).aspx

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM