/// http://jeanne.wankuma.com/tips/csharp/directory/getfilesmostdeep.html /// --------------------------------------------------------------------------------------- /// <summary> /// 指定した検索パターンに一致するファイルを最下層まで検索しすべて返します。</summary> /// <param name="stRootPath"> /// 検索を開始する最上層のディレクトリへのパス。</param> /// <param name="stPattern"> /// パス内のファイル名と対応させる検索文字列。</param> /// <returns> /// 検索パターンに一致したすべてのファイルパス。</returns> /// --------------------------------------------------------------------------------------- public static string[] GetFilesMostDeep(string stRootPath, string stPattern) { // ファイルリスト取得開始をデバッグ出力 Debug.Print(DateTime.Now + " Started to get files recursivery."); StringCollection hStringCollection = new StringCollection(); // このディレクトリ内のすべてのファイルを検索する foreach (string stFilePath in Directory.GetFiles(stRootPath, stPattern)) { hStringCollection.Add(stFilePath); Debug.Print(DateTime.Now + " Found image file, Filename = " + stFilePath); } // このディレクトリ内のすべてのサブディレクトリを検索する (再帰) foreach (string stDirPath in Directory.GetDirectories(stRootPath)) { string[] stFilePathes = GetFilesMostDeep(stDirPath, stPattern); // 条件に合致したファイルがあった場合は、ArrayList に加える if (stFilePathes != null) { hStringCollection.AddRange(stFilePathes); } } // StringCollection を 1 次元の String 配列にして返す string[] stReturns = new string[hStringCollection.Count]; hStringCollection.CopyTo(stReturns, 0); // ファイルリスト取得終了をデバッグ出力 Debug.Print(DateTime.Now + " Finished to get files recursivery."); return stReturns; }
public CompilerParameters (string[] assemblyNames, string output, bool includeDebugInfo) { referencedAssemblies = new StringCollection(); referencedAssemblies.AddRange (assemblyNames); outputAssembly = output; includeDebugInformation = includeDebugInfo; }
public static StringCollection ToCollection(string multiline) { var collection = new StringCollection(); var lines = GetLines(multiline); collection.AddRange(lines.ToArray()); return collection; }
public static SPList EnsureStatsList(SPWeb web) { var list = web.Lists.TryGetList("Stats"); if (list != null) return list; var teamsList = web.Lists["Teams"]; var fields = new List<Field> { new LookupField {Title = "Team", LookupList = teamsList.ID, Required = true, Hidden = true}, new Field {Title = "Time", Type = SPFieldType.DateTime, Required = true}, new Field {Title = "Question", Type = SPFieldType.Text, Required = false, Hidden = true}, new Field {Title = "Answer", Type = SPFieldType.Text, Required = false}, new Field {Title = "Points", Type = SPFieldType.Number, Required = false}, new Field {Title = "Level", Type = SPFieldType.Number, Required = false, Hidden = true}, }; list = BuildList(web, "Stats", fields); // Read items that were created by the user list.ReadSecurity = 2; // Create and Edit access: None list.WriteSecurity = 4; list.Update(); var view = list.DefaultView; view.ViewFields.Delete("LinkTitle"); view.Update(); var titleField = list.Fields.GetFieldByInternalName("LinkTitle"); titleField.Hidden = true; titleField.ShowInViewForms = false; titleField.Update(); var viewFields = new StringCollection(); viewFields.AddRange(fields.Select(field => field.Title).ToArray()); list.Views.Add("Godmode", viewFields, null, 100, true, false, SPViewCollection.SPViewType.Html, true); return list; }
/// <summary> /// Class constructor /// </summary> /// <param name="schema">The schema for the 2da. The schema defines /// the columns contained in the 2da</param> public _2DA(string[] schema) : this() { StringCollection schemaColl = new StringCollection(); schemaColl.AddRange(schema); SetSchema(schemaColl); }
static void Main(string[] args) { System.Collections.Specialized.StringCollection stringCollection = new System.Collections.Specialized.StringCollection(); String[] Cities = new String[] { "Hyderabad", "Delhi", "Mumbai", "Banglore", "Chennai", "Kolkatta" }; stringCollection.AddRange(Cities); // Display the contents of the collection using foreach. Console.WriteLine("Displays the elements using foreach:"); foreach (String obj in stringCollection) { Console.WriteLine(" {0}", obj); } Console.WriteLine(); stringCollection.Add("Pune"); stringCollection.Add("Vizag"); stringCollection.Remove("Chennai"); Console.WriteLine("After Updating Collection:"); foreach (String obj in stringCollection) { Console.WriteLine(" {0}", obj); } Console.WriteLine(); // Copy the collection to a new array starting at index 0. String[] CitiesArray = new String[stringCollection.Count]; stringCollection.CopyTo(CitiesArray, 0); Console.WriteLine("The new array contains:"); for (int i = 0; i < CitiesArray.Length; i++) { Console.WriteLine(" [{0}] {1}", i, CitiesArray[i]); } Console.WriteLine(); Console.ReadLine(); }
/// <summary> /// Compares two datatables and filters out all matching rows. The columns in the two tables must be the same. /// </summary> /// <param name="source">The source table to compare.</param> /// <param name="destination">The destination table to compare.</param> /// <param name="keycolumns">The column that identifies the row.</param> /// <param name="ignorecolumns">A collection of columns to ignore when comparing.</param> public static void FilterMatches(DataTable source, DataTable destination, string[] keycolumns, string[] ignorecolumns) { StringCollection ignorecols = new StringCollection(); if(ignorecolumns != null) ignorecols.AddRange(ignorecolumns); for(int i = source.Rows.Count - 1; i >= 0; i--) { DataRow sourcerow = source.Rows[i]; // Locate the row in the destination table string select = string.Empty; foreach(string keycolumn in keycolumns) { select += string.Format("{0}='{1}' AND ", keycolumn, sourcerow[keycolumn]); } select = select.Substring(0, select.Length - 5); DataRow[] rows = destination.Select(select); // Select matching rows if(rows.Length > 0) { DataRow destrow = rows[0]; if(CompareColumns(source, sourcerow, destrow, ignorecols)) { // Rows are matching, remove them source.Rows.Remove(sourcerow); destination.Rows.Remove(destrow); } } } }
/// <summary> /// Se chua nhung muc tin tuc, vi du: Tin Tinh Uy, Hoi Dong Nhan Dan, Thong tin lanh dao, So ban nghanh, dia phuong, doanh nghiep /// </summary> /// <param name="web"></param> public static void CreateNewsCategoryList(SPWeb web) { var helper = new ListHelper(web) { Title = ListsName.VietNamese.NewsCategory, Name = ListsName.English.NewsCategory, OnQuickLaunch = true }; helper.AddField(new LookupFieldCreator(FieldsName.NewsCategory.English.ParentName, FieldsName.NewsCategory.VietNamese.ParentName) { LookupList = ListsName.English.NewsCategory, LookupField = FieldsName.NewsCategory.English.Heading }); StringCollection collect1 = new StringCollection(); collect1.AddRange(new string[] { FieldsName.NewsCategory.FieldValuesDefault.TinTuc, FieldsName.NewsCategory.FieldValuesDefault.DoanhNghiep, FieldsName.NewsCategory.FieldValuesDefault.DuLich, FieldsName.NewsCategory.FieldValuesDefault.TinhUy }); helper.AddField(new ChoiceFieldCreator(FieldsName.NewsCategory.English.TypeCategory, FieldsName.NewsCategory.VietNamese.TypeCategory) { Choices = collect1 }); helper.AddField(new BooleanFieldCreator(FieldsName.NewsCategory.English.Status, FieldsName.NewsCategory.VietNamese.Status)); SPList list = helper.Apply(); var title = list.Fields.GetFieldByInternalName(FieldsName.Title); title.Title = FieldsName.NewsCategory.English.Heading; title.Update(); list.EnableAttachments = true; list.Update(); }
public static StringCollection ToStringCollection(string text) { string[] sep = {"\\n"}; string[] strs = text.Split(sep, StringSplitOptions.None); StringCollection coll = new StringCollection(); coll.AddRange(strs); return coll; }
/// <summary> /// Creates a shallow copy of the specified <see cref="StringCollection" />. /// </summary> /// <param name="stringCollection">The <see cref="StringCollection" /> that should be copied.</param> /// <returns> /// A shallow copy of the specified <see cref="StringCollection" />. /// </returns> public static StringCollection Clone(StringCollection stringCollection) { string[] strings = new string[stringCollection.Count]; stringCollection.CopyTo(strings, 0); StringCollection clone = new StringCollection(); clone.AddRange(strings); return clone; }
public override void ShellCalled(string identifier, string[] files) { if (identifier == "up") { StringCollection arr = new StringCollection(); arr.AddRange(files); UploadFiles(arr); } }
protected void BuildPropertySet(Type p, StringCollection propertySet) { if (TypeToLdapPropListMap[this.MappingTableIndex].ContainsKey(p)) { Debug.Assert(TypeToLdapPropListMap[this.MappingTableIndex].ContainsKey(p)); string[] props = new string[TypeToLdapPropListMap[this.MappingTableIndex][p].Count]; TypeToLdapPropListMap[this.MappingTableIndex][p].CopyTo(props, 0); propertySet.AddRange(props); } else { Type baseType; if (p.IsSubclassOf(typeof(UserPrincipal))) { baseType = typeof(UserPrincipal); } else if (p.IsSubclassOf(typeof(GroupPrincipal))) { baseType = typeof(GroupPrincipal); } else if (p.IsSubclassOf(typeof(ComputerPrincipal))) { baseType = typeof(ComputerPrincipal); } else if (p.IsSubclassOf(typeof(AuthenticablePrincipal))) { baseType = typeof(AuthenticablePrincipal); } else { baseType = typeof(Principal); } Hashtable propertyList = new Hashtable(); // Load the properties for the base types... foreach (string s in TypeToLdapPropListMap[this.MappingTableIndex][baseType]) { if (!propertyList.Contains(s)) { propertyList.Add(s, s); } } // Reflect the properties off the extension class and add them to the list. BuildExtensionPropertyList(propertyList, p); foreach (string property in propertyList.Values) { propertySet.Add(property); } // Cache the list for this property type so we don't need to reflect again in the future. this.AddPropertySetToTypePropListMap(p, propertySet); } }
public static void MyStringCol() { StringCollection MyStringCol = new StringCollection(); String[] myArray = new String[] { "NumberOfLines", "Line", "DownsAfterLine" }; MyStringCol.AddRange(myArray); //Copies the Array "myArray" to the End of the StringCollection "MyString" Console.WriteLine("Initial contents of the StringCollection:"); PrintValues(MyStringCol); }
public static DataObject GetDataObject(IEnumerable<string> paths, bool includeAsText = true) { var dataObject = new DataObject(); var pathCollection = new StringCollection(); pathCollection.AddRange(paths.ToArray()); dataObject.SetFileDropList(pathCollection); if (includeAsText) dataObject.SetText(string.Join(Environment.NewLine, paths)); return dataObject; }
public static bool ToAppBoolean(object mDbBoolean) { StringCollection BooleanTrueValues = new StringCollection(); BooleanTrueValues.AddRange(new string[] { "1", "S", "Y", "T", "V", "TRUE", "VERDADERO" }); if (BooleanTrueValues.Contains(mDbBoolean.ToString().ToUpper())) return true; return false; }
protected void ProcessView(object modelHost, SPList targetList, ListViewDefinition viewModel) { var currentView = targetList.Views.FindByName(viewModel.Title); InvokeOnModelEvent(this, new ModelEventArgs { CurrentModelNode = null, Model = null, EventType = ModelEventType.OnProvisioning, Object = currentView, ObjectType = typeof(SPView), ObjectDefinition = viewModel, ModelHost = modelHost }); if (currentView == null) { var viewFields = new StringCollection(); viewFields.AddRange(viewModel.Fields.ToArray()); // TODO, handle personal view creation currentView = targetList.Views.Add(viewModel.Title, viewFields, viewModel.Query, (uint)viewModel.RowLimit, viewModel.IsPaged, viewModel.IsDefault); } // viewModel.InvokeOnDeployingModelEvents<ListViewDefinition, SPView>(currentView); // if any fields specified, overwrite if (viewModel.Fields.Any()) { currentView.ViewFields.DeleteAll(); foreach (var viewField in viewModel.Fields) currentView.ViewFields.Add(viewField); } // viewModel.InvokeOnModelUpdatedEvents<ListViewDefinition, SPView>(currentView); InvokeOnModelEvent(this, new ModelEventArgs { CurrentModelNode = null, Model = null, EventType = ModelEventType.OnProvisioned, Object = currentView, ObjectType = typeof(SPView), ObjectDefinition = viewModel, ModelHost = modelHost }); currentView.Update(); }
private void busButton_CheckedChanged(object sender, EventArgs e) { CheckBox button = sender as CheckBox; mStopTimes.SetIncluded(button.Text, button.Checked); CreateStopTimesView(); UpdateView(); StringCollection excludedBuses = new StringCollection(); excludedBuses.AddRange(mStopTimes.ExcludedBuses); Settings.Default.ExcludedBuses = excludedBuses; Settings.Default.Save(); }
private void _aimTCGAServiceComboBox_KeyDown(object sender, KeyEventArgs e) { if (_aimTCGAServiceComboBox.DroppedDown && _aimTCGAServiceComboBox.SelectedIndex != -1 && e.KeyCode == Keys.Delete) { e.Handled = true; var sl = new StringCollection(); sl.AddRange(CollectionUtils.ToArray<string>(_component.AIMTCGAServiceList)); sl.RemoveAt(_aimTCGAServiceComboBox.SelectedIndex); _component.AIMTCGAServiceList = sl; } }
[Test] public void Test_04_GetUserRoles() { Proxy.AdminRef.Admin admin = new Proxy.AdminRef.Admin( ); admin.Url = Globals.AdminUrl(); admin.Credentials = System.Net.CredentialCache.DefaultCredentials.GetCredential(new Uri(Globals.SharePointTestServer), ""); string[] roles = admin.GetUserRoles(Globals.SiteCollectionForCreationTests(), @"WSDEV\lnpair"); Assert.IsTrue(roles.Length == 2, "The user is both a Reader and a Contributor"); StringCollection roleList = new StringCollection(); roleList.AddRange(roles); Assert.IsTrue(roleList.Contains("Read"), @"WSDEV\lnpair is a Reader on this site. Really!"); Assert.IsTrue(roleList.Contains("Contribute"), @"WSDEV\lnpair is a Contributor on this site. Really!"); }
public SiteColumnCustom(string name, SPFieldType columnType, string group, string[] choices = null, bool dateOnly = false) { Name = name; ColumnType = columnType; Group = group; DateOnly = dateOnly; if (choices != null) { StringCollection choiceCollection = new StringCollection(); choiceCollection.AddRange(choices); Choices = choiceCollection; } }
/// <summary> /// Returns languages of given settings path /// </summary> /// <param name="project">EPLAN project</param> /// <param name="settingsPath">EPLAN settings path</param> /// <returns>Language list</returns> private static StringCollection GetLanguages(Project project, string settingsPath) { using (new LockingStep()) { ProjectSettings projectSettings = new ProjectSettings(project); var displayLanguagesString = projectSettings.GetStringSetting(settingsPath, 0); var languages = new StringCollection(); var languagesFromSettings = displayLanguagesString.Split(';') .Where(s => !string.IsNullOrWhiteSpace(s)).Distinct().ToArray(); // remove empty languages.AddRange(languagesFromSettings); return languages; } }
private void buttonSaveSettings_Click(object sender, EventArgs e) { Settings.Default.OohSheetLocation = textboxOohSheetLocation.Text; Settings.Default.EmailAddressUsername = textBoxEmailAddress.Text; Settings.Default.EmailAddressPassword = Utility.EncryptString(Utility.ToSecureString(textBoxPassword.Text)); Settings.Default.GoogleWorkGroupName = textBoxGoogleWorkGroupName.Text; StringCollection initialsToIgnore = new StringCollection(); initialsToIgnore.AddRange(textBoxInitialsToIgnore.Text.Split(',')); Settings.Default.InitialsToIgnore = initialsToIgnore; Settings.Default.Save(); buttonPreviewChanges.Enabled = true; }
public void Test01() { StringCollection sc; // simple string values string[] values = { "", " ", "a", "aa", "text", " spaces", "1", "$%^#", "2222222222222222222222222", System.DateTime.Today.ToString(), Int32.MaxValue.ToString() }; // [] StringCollection.IsReadOnly should return false //----------------------------------------------------------------- sc = new StringCollection(); // [] on empty collection // if (sc.IsReadOnly) { Assert.False(true, string.Format("Error, returned true for empty collection")); } // [] on filled collection // sc.Clear(); sc.AddRange(values); if (sc.Count != values.Length) { Assert.False(true, string.Format("Error, count is {0} instead of {1}", sc.Count, values.Length)); } if (sc.IsReadOnly) { Assert.False(true, string.Format("Error, returned true for filled collection")); } }
/// <summary> /// Loads the stop words used in the search feature. /// </summary> /// <returns></returns> public override StringCollection LoadStopWords() { string fileName = _Folder + "stopwords.txt"; if (!File.Exists(fileName)) return new StringCollection(); using (StreamReader reader = new StreamReader(fileName)) { string file = reader.ReadToEnd(); string[] words = file.Split(new char[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries); StringCollection col = new StringCollection(); col.AddRange(words); return col; } }
protected void Page_Load(object sender, System.EventArgs e) { // Put user code to initialize the page here page_utilities.Set_titles(this, "RFG User Guide"); if (check_permissions(this.Page, false) == null) { StringCollection it_visible = new StringCollection(); it_visible.AddRange(new string[2]{"home", "guide"}); StringCollection it_invisible = new StringCollection(); it_invisible.AddRange(new string[3]{"guide_0", "guide_1", "guide_2"}); page_utilities.modify_leftnav(this.Page, it_visible, it_invisible); } }
/// <summary> /// Parse groups out of an input string based on the opening and closing characters /// </summary> /// <param name="input">The input to parse</param> /// <param name="openingChar">The opening character of a grouping</param> /// <param name="closingChar">The closing character of a grouping</param> /// <returns>The complete first level groups found</returns> public static string[] ParseFirstLevelGroups(string input, char openingChar, char closingChar) { StringCollection groups = new StringCollection(); char[] delimiters = new char[] { openingChar, closingChar }; int ind = input.IndexOfAny(delimiters); if (ind >= 0) groups.AddRange(input.Substring(0, ind).Trim().Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)); int count = 0; int start = ind; while (ind >= 0) { if (input[ind] == openingChar) count++; else if (input[ind] == closingChar) count--; if (count == 0) { string chunk = input.Substring(start + 1, ind - start - 1).Trim(); //chunk = chunk.Replace(Constants.SubcommandEnterSymbol, Constants.EscapeCharacter + Constants.SubcommandEnter); //chunk = chunk.Replace(Constants.SubcommandExitSymbol, Constants.EscapeCharacter + Constants.SubcommandExit); groups.Add(chunk); start = ind + 1; } if (start + 1 < input.Length) { ind = input.IndexOfAny(delimiters, ind + 1); if (ind >= 0 && count == 0) { groups.AddRange(input.Substring(start + 1, ind - start - 1).Trim().Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)); start = ind; } } else break; } if (start + 1 < input.Length) groups.AddRange(input.Substring(start + 1, input.Length - start - 1).Trim().Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)); string[] output = new string[groups.Count]; groups.CopyTo(output, 0); return output; }
protected void CreateList() { try { // choose your site SPWeb web = SPContext.Current.Web; SPListCollection lists = web.Lists; // create new Generic list called "AlertsList" lists.Add("AlertsList", "List to control the alerts for this webpart. Don't change the columns", SPListTemplateType.GenericList); SPList list = web.Lists["AlertsList"]; StringCollection categories = new StringCollection(); categories.AddRange(new string[] { "High", "Medium", "Low" }); // create Text type new column called "My Column" list.Fields.Add("Description", SPFieldType.Text, true); list.Fields.Add("Impact", SPFieldType.Choice, true, false, categories); list.Fields.Add("Pin to top", SPFieldType.Boolean, true); //get the newly added choice field instance SPFieldChoice fieldImpact = (SPFieldChoice)list.Fields["Impact"]; //set field format type i.e. radio/dropdown fieldImpact.EditFormat = SPChoiceFormatType.Dropdown; list.Update(); // make new column visible in default view SPView view = list.DefaultView; view.ViewFields.Add("Description"); view.ViewFields.Add("Impact"); view.ViewFields.Add("Pin to top"); view.Update(); Label myLabel = new Label(); myLabel.Text = "AlertsList Created. Please go to site contents to add items for the alerts"; this.Controls.Add(myLabel); } catch (Exception e) { } }
[Test] public void Test_01_ListAvailableSiteTemplates() { Proxy.AdminRef.Admin admin = new Proxy.AdminRef.Admin( ); admin.Url = Globals.AdminUrl(); admin.Credentials = System.Net.CredentialCache.DefaultCredentials.GetCredential(new Uri(Globals.SharePointTestServer), ""); string[] templates = admin.ListAvailableSiteTemplates(Globals.SiteCollectionForTests()); StringCollection tpls = new StringCollection(); tpls.AddRange(templates); Assert.IsTrue(tpls.Contains("Team Site"), "Template is missing: Team Site"); Assert.IsTrue(tpls.Contains("Blank Site"), "Template is missing: Blank Site"); Assert.IsTrue(tpls.Contains("Document Workspace"), "Template is missing: Document Workspace"); Assert.IsTrue(tpls.Contains("Basic Meeting Workspace"), "Template is missing: Basic Meeting Workspace"); Assert.IsTrue(tpls.Contains("Blank Meeting Workspace"), "Template is missing: Blank Meeting Workspace"); Assert.IsTrue(tpls.Contains("Decision Meeting Workspace"), "Template is missing: Decision Meeting Workspace"); Assert.IsTrue(tpls.Contains("Social Meeting Workspace"), "Template is missing: Social Meeting Workspace"); Assert.IsTrue(tpls.Contains("Multipage Meeting Workspace"), "Template is missing: Multipage Meeting Workspace"); }
public static void LearnStringCollection() { Console.WriteLine("From LearnStringCollection Method"); System.Collections.Specialized.StringCollection strCollection = new System.Collections.Specialized.StringCollection(); String[] arString = new String[] { "ATUL", "THERAN" }; strCollection.AddRange(arString); strCollection.Add("atul"); //Adding same in another case strCollection.Add("THERAN"); //Adding duplicate foreach (var item in strCollection) { Console.WriteLine(item); } for (int i = 0; i < strCollection.Count; i++) { Console.WriteLine($"Value at index # {i} is {strCollection[i]}"); } }
/// <summary> /// Evaulate the path string in relation to the current item /// </summary> /// <param name="context">The Revolver context to evaluate the path against</param> /// <param name="path">The path to evaulate. Can either be absolute or relative</param> /// <returns>The full sitecore path to the target item</returns> public static string EvaluatePath(Context context, string path) { if (ID.IsID(path)) return path; string workingPath = string.Empty; if (!path.StartsWith("/")) workingPath = context.CurrentItem.Paths.FullPath + "/" + path; else workingPath = path; // Strip any language and version tags if (workingPath.IndexOf(':') >= 0) workingPath = workingPath.Substring(0, workingPath.IndexOf(':')); // Make relative paths absolute string[] parts = workingPath.Split('/'); StringCollection targetParts = new StringCollection(); targetParts.AddRange(parts); while (targetParts.Contains("..")) { int ind = targetParts.IndexOf(".."); targetParts.RemoveAt(ind); if (ind > 0) { targetParts.RemoveAt(ind - 1); } } if (targetParts[targetParts.Count - 1] == ".") targetParts.RemoveAt(targetParts.Count - 1); // Remove empty elements while (targetParts.Contains("")) { targetParts.RemoveAt(targetParts.IndexOf("")); } string[] toRet = new string[targetParts.Count]; targetParts.CopyTo(toRet, 0); return "/" + string.Join("/", toRet); }
/// <summary> /// Loads the stop words used in the search feature. /// </summary> /// <returns> /// A StringCollection. /// </returns> public override StringCollection LoadStopWords() { var fileName = string.Format("{0}stopwords.txt", this.Folder); if (!File.Exists(fileName)) { return new StringCollection(); } using (var reader = new StreamReader(fileName)) { var file = reader.ReadToEnd(); var words = file.Split(new[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries); var col = new StringCollection(); col.AddRange(words); return col; } }
public void ListBoxMultiSelection() { ListBoxTester myListBox = new ListBoxTester("myListBox"); string[] alternateColors = new string[] {"Red", "Yellow", "Blue", "Violet"}; StringCollection alternates = new StringCollection(); alternates.AddRange(alternateColors); myListBox.ClearSelected(); foreach(string color in alternates) { myListBox.SetSelected(color, true); } Assert.AreEqual(4, myListBox.Properties.SelectedItems.Count); foreach(object selectedItem in myListBox.Properties.SelectedItems) { Assert.IsTrue(alternates.Contains(Convert.ToString(selectedItem))); } }